我有一个包含四列的数据网格视图:
productid
productname
productprice
buy (this is button column )
是否可以找到按钮列的点击事件?我的意思是,如果我单击第 1 行按钮,相应的行值将被转移到另一个表单。
如果我单击第 2 行按钮,则相应的值将传输到另一个表单。我正在做 WinForms 应用程序。任何想法或示例代码将不胜感激。
我有一个包含四列的数据网格视图:
productid
productname
productprice
buy (this is button column )
是否可以找到按钮列的点击事件?我的意思是,如果我单击第 1 行按钮,相应的行值将被转移到另一个表单。
如果我单击第 2 行按钮,则相应的值将传输到另一个表单。我正在做 WinForms 应用程序。任何想法或示例代码将不胜感激。
这在DataGridViewButtonColumn的 MSDN 页面上得到了回答。
您需要处理 DataGridView 的 CellClick 或 CellContentClick 事件。
要附加处理程序:
dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
以及处理事件的方法中的代码
void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
// Check that the button column was clicked
if (dataGridView1.Columns[e.ColumnIndex].Name == "MyButtonColumn")
{
// Here you call your method that deals with the row values
// you can use e.RowIndex to find the row
// I also use the row's databounditem property to get the bound
// object from the DataGridView's datasource - this only works with
// a datasource for the control but 99% of the time you should use
// a datasource with this control
object item = dataGridView1.Rows[e.RowIndex].DataBoundItem;
// I'm also just leaving item as type object but since you control the form
// you can usually safely cast to a specific object here.
YourMethod(item);
}
}
使用验证单元格,您可以获得(单元格的列和行)。将按钮初始化为win表单按钮对象,还添加一个调用相同单击事件的处理程序。