2 回答

TA貢獻1772條經驗 獲得超8個贊
您可以使用該Control.Tag屬性checkedListBox在每個按鈕中存儲正確的引用:
首先,在 中分配checkedListBox控件引用Form_Load:
btnSelectAll1.Tag = checkedListBox1;
btnSelectAll2.Tag = checkedListBox2;
...
btnSelectAll10.Tag = checkedListBox10;
然后,為所有這些按鈕創建一個事件處理程序(確保將 Form.Designer.cs 文件中每個按鈕的事件指向此事件處理程序):Click
private void SelectAll_Click(object sender, EventArgs e)
{
var clickedButton = sender as Button;
var checkedListBoxControl = clickedButton.Tag as CheckedListBox;
// Do what you need with checkedListBoxControl...
}

TA貢獻1808條經驗 獲得超4個贊
很簡單,在 winforms 中的每個事件中,發送者都是引發事件的對象。
Button button1 = new Button() {...}
Button button2 = new Button() {...}
button1.OnClicked += this.OnButtonClicked;
button2.OnClicked += this.OnButtonClicked;
// both buttons will call OnButtonClicked when pressed
您也可以在 Visual Studio Designer 中使用帶有閃電標記的選項卡在屬性窗口中執行此操作。只需選擇您以前使用過的功能。
private void OnButtonClicked(object sender, EventArgs e)
{
Button button = (Button)sender;
// now you know which button was clicked
...
}
如果您讓其他項目也調用此偶數處理程序,請小心
ListBox listBox = new ListBox();
listBox.OnClicked += this.OnButtonClicked;
private void OnButtonClicked(object sender, EventArgs e)
{
// sender can be either a Button or a ListBox:
switch (sender)
{
case Button button:
ProcesButtonPressed(button);
break;
case ListBox listBox:
ProcessListBoxPressed(listBox);
break;
}
}
這個 switch 語句對你來說可能是新的。請參閱C# 7 中的模式匹配
- 2 回答
- 0 關注
- 103 瀏覽
添加回答
舉報