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

本文关键字:异常 未处理 转换 无效 | 更新日期: 2023-09-27 18:33:15

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

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

您正在尝试将EventArgs(parent type)转换为DataGridViewCellEventArgs(child type)。在这种情况下,这是不安全的。您可以创建一个新DataGridViewCellEventArgs

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

在这里创建了一个新DataGridViewCellEventArgs。由于它是单元格相关操作的 Event 参数,因此需要columnIndexrowIndex来定位单元格。