0

我想尝试在函数内部调用一个事件,而我想调用的事件是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 所做的任何更改

4

1 回答 1

1

You are trying to cast EventArgs(parent type) to DataGridViewCellEventArgs(child type). This is not safe at this scenario. You can create a new DataGridViewCellEventArgs.

var _productCode = dataGridView1["Product Code",(new DataGridViewCellEventArgs(columnIndex, rowIndex)).RowIndex].Value;

Here a new DataGridViewCellEventArgs is created. Since it is a Event argument for a cell related action a columnIndex and rowIndex is needed to locate the cell.

于 2013-09-27T18:21:41.760 回答