我想尝试在函数内调用一个事件,我想调用的事件是DataGridViewCellEventArgs
,但它在函数内部。但是,当我尝试下面的代码时,我收到了这个错误:Unable to cast object of type 'System.Windows.Forms.MouseEventArgs' to type 'System.Windows.Forms.DataGridViewCellEventArgs'.
以下是代码:
private void UpdateQuantityDataGridView(object sender, EventArgs e)
{
(...Other codes)
var _productCode = dataGridView1["Product Code", ((DataGridViewCellEventArgs)e).RowIndex].Value;
(...Other codes)
}
当用户完成DataGridView
中的数据编辑并按“确定”按钮时,我调用上面的函数,上面的函数是更新用户对数据库以及DataGridView中所做的任何更改< / p>
答案 0 :(得分:1)
您正在尝试将EventArgs(parent type)
投射到DataGridViewCellEventArgs(child type)
。在这种情况下,这是不安全的。您可以创建新的DataGridViewCellEventArgs
。
var _productCode = dataGridView1["Product Code",(new DataGridViewCellEventArgs(columnIndex, rowIndex)).RowIndex].Value;
这里创建了一个新的DataGridViewCellEventArgs
。由于它是与单元格相关的操作的Event参数,因此需要columnIndex
和rowIndex
来定位单元格。