2013-09-27 33 views
0

我想嘗試調用函數內部的事件,並且我想調用的事件是DataGridViewCellEventArgs,但它在函數內部。但是,當我嘗試下面的代碼,我得到這個錯誤:Unable to cast object of type 'System.Windows.Forms.MouseEventArgs' to type 'System.Windows.Forms.DataGridViewCellEventArgs'.Invalid Cast Exception was unhandled

下面是代碼:

private void UpdateQuantityDataGridView(object sender, EventArgs e) 
     { 

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

     } 

我撥打以上功能,當用戶完成編輯數據DataGridView,然後按「確定」按鈕,上面的功能是更新用戶對數據庫以及DataGridView所做的任何更改。

回答

1

您正試圖將EventArgs(parent type)轉換爲DataGridViewCellEventArgs(child type)。在這種情況下這不安全。您可以創建一個新的DataGridViewCellEventArgs

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

這裏創建了一個新的DataGridViewCellEventArgs。由於它是與單元相關的動作的Event參數,所以需要columnIndexrowIndex來定位單元。

+0

什麼是colIndex和rowIndex先生? – Kaoru

相關問題