2013-09-27 39 views
0

如何調用函數內的事件?因爲我有一個錯誤Object reference not set to instance of an object和錯誤指出:_e.RowIndex調用函數c中的事件#

而我想知道如何調用一個函數內的事件。現在我可以從new EventHandler(....)調用事件,但現在我想調用一個函數內部的事件,它給我的錯誤Object reference not set to instance of an object

下面是代碼:

private void UpdateQuantityDataGridView(object sender, EventArgs e) 
{ 
    DataGridViewCellEventArgs _e = null; 

    cmdSelect.Parameters.Add("ProductCode" , System.Data.OleDb.OleDbType.VarChar) ; 
    cmdSelect.Parameters[ "ProductCode" ].Value = dataGridView1[ "Product Code" , _e.RowIndex].Value; 

} 

是上面的代碼中正確的方法來做到這一點?

EDITED

這是我調用的函數UpdateQuantityDataGridView

if (_choice.comboBox1.Text == "English") 
       { 
        System.Media.SoundPlayer _sounds = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav"); 
        _sounds.Play(); 
        MessageBox.Show("Updated Successfully!", "Updated"); 

        ShowButtons(sender, e); 

        DisableColumnEdited(sender, e); 

        UpdateQuantityDataGridView(sender, e); 
       } 

這裏是我的情況:

當DataGridView的用戶編輯數據,以及用戶點擊 「確定」 按鈕,上面的代碼將執行,並從DataGridView更新數據庫,這就是爲什麼我想在函數內部訪問DataGridViewCellEventArgs。我無法完成和工作,當我打電話通過使用new EventHandler(....)

+4

'_e = null'引用空引用將導致'NullReferenceException'。你想要達到什麼目標?你想要什麼'_e.RowIndex'返回? –

+0

'_e.RowIndex'是告訴程序從DataGridView中選擇了哪一行 – Kaoru

+1

讓我看看你的代碼在哪裏調用'UpdateQuantityDataGridView' –

回答

3

您正在設置_enull然後嘗試使用它將創建一個NullReferenceException(如您所發現的那樣)。

我想你想投eDataGridViewCellEventArgs而不是創建一個新的變量。

private void UpdateQuantityDataGridView(object sender, EventArgs e) 
{ 
    cmdSelect.Parameters.Add("ProductCode" , System.Data.OleDb.OleDbType.VarChar) ; 
    cmdSelect.Parameters[ "ProductCode" ].Value = dataGridView1[ "Product Code" , ((DataGridViewCellEventArgs)e).RowIndex].Value; 

} 

(正如在評論中提到,這是假定你傳遞的DataGridViewCellEventArs一個實例e。)

+0

,肯定不會工作,因爲'e'是'EventArgs'類型。 –

+0

我試過'dataGridView [「Product Code」,(DataGridViewCellEventArgs)_e.RowIndex] .Value' 但是'_e'在當前內容中不存在。 – Kaoru

+1

@neoistheone和'DataGridViewCellEventArgs'是從'EventArgs'派生出來的,所以它可以工作,如果這是'e'傳入的內容,這一切都取決於如何調用'UpdateQuantityDataGridView',我們需要看到代碼在哪裏他可以訂閱該事件或自己調用該函數。 –

4

您正在將變量_e設置爲空。然後,當您從未設置時引用_e.RowIndex。

+1

我刪除了「不能留下評論」位。你所說的是答案,不需要把它作爲評論。 –

0

要設置_enull

然後,您嘗試訪問其RowIndex屬性,這是什麼投擲NullReferenceException

你所有的代碼示例試圖做的是將一個參數添加到cmdSelect。你究竟想要完成什麼?

+0

問題可以在評論中 –