winform中怎样使DataGridView的某一列可以添加两个Button控件

时间:2022-08-16 19:32:23

参考地址:

http://topic.csdn.net/u/20100225/13/34310e66-4de2-4293-ac89-a8cee1accf7a.html

 

参考代码:

 1 private void Form1_Load(object sender, EventArgs e)
 2         {
 3             this.dataGridView1.Columns.Add("a", "a");
 4             this.dataGridView1.Columns.Add("b", "b");
 5             this.dataGridView1.Columns.Add("c", "c");
 6 
 7             for (int i = 0; i < 3; i++)
 8                 this.dataGridView1.Rows.Add();
 9 
10             for (int i = 0; i < 3; i++) { Button[] btn = new Button[2];
11                 btn[0] = new Button();
12                 btn[0].Text = "one";
13                 btn[1] = new Button();
14                 btn[1].Text = "two";
15                 this.dataGridView1.Controls.Add(btn[0]);
16                 this.dataGridView1.Controls.Add(btn[1]);
17                 Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(2, i, false);
18                 btn[0].Size = btn[1].Size = new Size(rect.Width / 2, rect.Height);
19                 btn[0].Location = new Point(rect.Left, rect.Top);
20                 btn[1].Location = new Point(rect.Left + btn[0].Width, rect.Top);
21                 btn[0].Click += new EventHandler(CustomBtn_Click);
22                 btn[1].Click += new EventHandler(CustomBtn_Click);
23             }
24         }
25         void CustomBtn_Click(object sender, EventArgs e)
26         {
27             MessageBox.Show((sender as Button).Text);
28         }
29  
30 在有滚动条时,在下面的两个事件中重定位一下Button的位置:
31         //  滚动DataGridView时调整Button位置
32         private void DataGridView_Scroll(object sender, ScrollEventArgs e)
33         {
34         }
35         //  改变DataGridView列宽时调整Button位置
36         private void DataGridView_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
37         {
38         }

转自 http://blog.sina.com.cn/s/blog_43f5c8b4010129r3.html