简体   繁体   English

未处理无效的强制转换异常

[英]Invalid Cast Exception was unhandled

i want to try call an event inside a function and the event that i want to call is DataGridViewCellEventArgs , but it is inside a function. 我想尝试在函数内调用事件,而我想调用的事件是DataGridViewCellEventArgs ,但它在函数内。 But, when i tried below code, i got this error: Unable to cast object of type 'System.Windows.Forms.MouseEventArgs' to type 'System.Windows.Forms.DataGridViewCellEventArgs'. 但是,当我尝试下面的代码时,出现了此错误: Unable to cast object of type 'System.Windows.Forms.MouseEventArgs' to type 'System.Windows.Forms.DataGridViewCellEventArgs'.

Here is the code: 这是代码:

private void UpdateQuantityDataGridView(object sender, EventArgs e)
        {

           (...Other codes)
           var _productCode = dataGridView1["Product Code", ((DataGridViewCellEventArgs)e).RowIndex].Value;
           (...Other codes)

        }

I call above function when the user finish editing the data in DataGridView and press "OK" button, the function above is to update any changes that has been made by user to the Database as well as in DataGridView 当用户完成在DataGridView的数据编辑并按“确定”按钮时,我调用上面的函数,上面的函数是更新用户对数据库以及DataGridView中所做的任何更改

You are trying to cast EventArgs(parent type) to DataGridViewCellEventArgs(child type) . 您正在尝试将EventArgs(parent type)DataGridViewCellEventArgs(child type) This is not safe at this scenario. 在这种情况下,这是不安全的。 You can create a new DataGridViewCellEventArgs . 您可以创建一个新的DataGridViewCellEventArgs

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

Here a new DataGridViewCellEventArgs is created. 在这里创建一个新的DataGridViewCellEventArgs Since it is a Event argument for a cell related action a columnIndex and rowIndex is needed to locate the cell. 由于它是与单元格相关的操作的事件参数,因此需要columnIndexrowIndex来定位该单元格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM