【问题标题】:Invalid Cast Exception was unhandled无效的转换异常未处理
【发布时间】:2013-09-27 18:17:08
【问题描述】:

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

【问题讨论】:

    标签: c# datagridview


    【解决方案1】:

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

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

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

    【讨论】:

    • 什么是 colIndex 和 rowIndex 先生?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多