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 关注
- 116 浏览
添加回答
举报