2011-09-02 115 views
4

我在datagridview中有一个按钮单元格。当单击该按钮时,应显示另一个datagridview。对于按钮列中的每个按钮单击,新datagridview中的数据应该是不同的。我不知道如何实现每行不同的按钮单击事件。请帮助我使用示例代码。datagridview中的按钮单击事件

回答

7

对于DataGridViewButtonColumn中的按钮单元,您无法实现按钮单击事件。相反,您使用DataGridView的事件并确定事件是否为您的DataGridViewButtonColumn中的单元格激发。使用事件的DataGridViewCellEventArgs.RowIndex属性可以找出哪个行被点击。

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { 
    // Ignore clicks that are not in our 
    if (e.ColumnIndex == dataGridView1.Columns["MyButtonColumn"].Index && e.RowIndex >= 0) { 
     Console.WriteLine("Button on row {0} clicked", e.RowIndex); 
    } 
} 

关于DataGridViewButtonColumn class的MSDN文档有一个更完整的示例。

+8

我会用'dataGridView1_CellContentClick'。这种方式只会发生在按钮本身被点击的情况下,而不是填充空间。 – Igor

0

使用dataGridView1_CellContentClick,而不是dataGridView1_CellClick

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) 
{ 

    if (e.ColumnIndex == 8) //make sure button index here 
    { 
      //write your code here 
    } 

}