winform中怎样使DataGridView的某一列可以添加两个Button控件
我要在DataGridView里面添加一列
这一列里面的cell是两个Button按钮,系统提供的DataGridViewButtonColumn模板列只有一个按钮,不满足我的要求。在网上查了一下,估记得自己创建一个模板列了,可能要分别重写DataGridViewColumn和DataGridViewCell这两个类。不知道那位大虾有这方面的代码??????谢谢了
[解决办法]
mark,围观,等高手
必须在一个cell里放2个button吗?不能添加2列么
[解决办法]
先写一个有两个button的class, 再自定义一个Columns类,将有两个button的类引入到自定义的Columns类
[解决办法]
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) { }