2013-09-28 12 views
2

我的窗體上有這個函數參數類型的函數:調用內部有另一個函數的C#

private void UpdateQuantityDataGridView(object sender, DataGridViewCellEventArgs e) 
{ 
    (...codes) 
} 

,我想調用另一個函數內部的功能,比方說,當我點擊了「確定」按鈕,以下函數將運行並執行具有參數類型的以上函數。

private void button5_Click(object sender, EventArgs e) // This is the "OK" button click handler. 
{ 
    SubmitButton(sender, e); 
} 

private void SubmitButton(object sender, EventArgs e) // This is function of "OK" button 
{ 
    (...codes) 
    UpdateQuantityDataGridView("What should i put in here? I tried (sender, e), but it is useless") 
} 

我知道,這個功能運行時,我們把這樣的事情: dataGridView1.CellValueChanged += new DataGridViewSystemEventHandler(...);

但是,我不希望這樣,因爲如果在DataGridView中的單元格值已更改的功能纔會運行,我想要訪問該功能,當我點擊「確定」按鈕。但是,我應該在參數值中放入什麼?

回答

3

目前提取邏輯在UpdateQuantityDataGridView()方法,並把它變成一個名爲任何你想要一個新的public方法,那麼你就可以在你的類或引用您的類,像這樣的任何其他代碼的任何地方調用這個邏輯:

public void DoUpdateQuantityLogic() 
{ 
    // Put logic here 
} 

注意:如果你不實際使用sendere,那麼你就可以離開上述方法不帶參數,但如果你使用e,例如,那麼你需要有一個參數爲DoUpdateQuantityLogic()法覈算對於你正在使用的e對象的屬性是什麼。

現在,你甚至可以從你其他的方法DoUpdateQuantityLogic(),像這樣:

private void button5_Click(object sender, EventArgs e) // This is the "OK" button click handler. 
{ 
    DoUpdateQuantityLogic(); 
} 

private void SubmitButton(object sender, EventArgs e) // This is function of "OK" button 
{ 
    DoUpdateQuantityLogic(); 
} 

這樣就可以重新使用你的邏輯,並隔離功能爲使單元測試更加簡單,如果你選擇的方法以單元測試這個邏輯。

如果你有決心使用現有的基於事件的方法的基礎設施,那麼你可以通過null同時爲sendere事件處理程序的參數,如:

UpdateQuantityDataGridView(null, null); 
+0

感謝先生@Karl安德森,我得到它現在:) – Kaoru

1

您可以使用發件人,但你不能使用Ë因爲UpdateQuantityDataGridView需要é是類型DataGridViewCellEventArgs的。

根據處理程序要與ê參數做什麼你UpdateQuantityDataGridView,你可以只通過當您從提交按鈕調用它。 否則,您將必須 a DataGridViewCellEventArgs並使用您自己的處理程序需要/期望的適當值填充它。

2

如果你的方法UpdateQuantityDataGridView()實際上使用參數sendere?如果不是兩者都傳遞null。

UpdateQuantityDataGridView(null, null); 

如果您使用的是他們:

var e = new DataGridViewCellEventArgs(); 
// assign any properties 
UpdateQuantityDataGridView(dataGridView1, e); 
+0

感謝先生@luisperezphd,我得到它現在:) – Kaoru

相關問題