简体   繁体   中英

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. 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'.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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