日期:2014-05-18 浏览次数:21438 次
if(dataGridView1.CurrentCell.OwningColumn.Name=="列名") { button1.visable=true; button2.visable=true; button1.Left = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Left; button1.Top = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Top; button1.Width = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Width; this.dataGridView1.Controls.Add(button1); button2.Left = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Left; button2.Top = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Top; button2.Width = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Width; this.dataGridView1.Controls.Add(button2); } else { button1.visable=false; button2.visable=false; }
------解决方案--------------------
添加一个DataGridView控件, 然后使用下面的代码试试:
private void Form1_Load(object sender, EventArgs e) { this.dataGridView1.Columns.Add("a", "a"); this.dataGridView1.Columns.Add("b", "b"); this.dataGridView1.Columns.Add("c", "c"); for (int i = 0; i < 3; i++) this.dataGridView1.Rows.Add(); for (int i = 0; i < 3; i++) { Button[] btn = new Button[2]; btn[0] = new Button(); btn[0].Text = "one"; btn[1] = new Button(); btn[1].Text = "two"; this.dataGridView1.Controls.Add(btn[0]); this.dataGridView1.Controls.Add(btn[1]); Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(2, i, false); btn[0].Size = btn[1].Size = new Size(rect.Width / 2, rect.Height); btn[0].Location = new Point(rect.Left, rect.Top); btn[1].Location = new Point(rect.Left + btn[0].Width, rect.Top); btn[0].Click += new EventHandler(CustomBtn_Click); btn[1].Click += new EventHandler(CustomBtn_Click); } } void CustomBtn_Click(object sender, EventArgs e) { MessageBox.Show((sender as Button).Text); }
------解决方案--------------------
在下面的两个事件中重定位一下Button的位置:
// 滚动DataGridView时调整Button位置 private void DataGridView_Scroll(object sender, ScrollEventArgs e) { } // 改变DataGridView列宽时调整Button位置 private void DataGridView_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e) { }