影响多个表单对象的函数(checkedListBox)

我在一个表单上有多个checkedListBox。对于每个checkedListBox,我都有一个“全选”项目的按钮:


private void btnSelectAll1_Click(object sender, EventArgs e)

{

    for (int i = 0; i < checkedListBox1.Items.Count; i++)

    {

        checkedListBox1.SetItemCheckState(i, CheckState.Checked);

    }

}

每个按钮都具有与checkedListBox2、3、4等相同的功能。


我不想复制每个单击功能中的代码,而是简单地使用一个替换按钮对应的“checkedListBox”的功能。例如,“btnSelectAll1”将“checkedListBox1”发送给函数,“btnSelectAll2”发送“checkedListBox2”等等。


就像是:


private void btnSelectAll1_Click(object sender, EventArgs e)

{

    SelectAll(checkedListBox1)

}


private void btnSelectAll2_Click(object sender, EventArgs e)

{

    SelectAll(checkedListBox2)

}


void SelectAll(strCheckedListBox)

{

    for (int i = 0; i < strCheckedListBox.Items.Count; i++)

    {

        strCheckedListBox.SetItemCheckState(i, CheckState.Checked);

    }

}


陪伴而非守候
浏览 117回答 2
2回答

料青山看我应如是

您可以使用该Control.Tag属性checkedListBox在每个按钮中存储正确的引用:首先,在 中分配checkedListBox控件引用Form_Load:btnSelectAll1.Tag = checkedListBox1;btnSelectAll2.Tag = checkedListBox2;...btnSelectAll10.Tag = checkedListBox10;然后,为所有这些按钮创建一个事件处理程序(确保将 Form.Designer.cs 文件中每个按钮的事件指向此事件处理程序):Clickprivate void SelectAll_Click(object sender, EventArgs e){&nbsp; &nbsp; var clickedButton = sender as Button;&nbsp; &nbsp; var checkedListBoxControl = clickedButton.Tag as CheckedListBox;&nbsp; &nbsp; // Do what you need with checkedListBoxControl...&nbsp;}

炎炎设计

很简单,在 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){&nbsp; &nbsp; Button button = (Button)sender;&nbsp; &nbsp; // now you know which button was clicked&nbsp; &nbsp; ...}如果您让其他项目也调用此偶数处理程序,请小心ListBox listBox = new ListBox();listBox.OnClicked += this.OnButtonClicked;private void OnButtonClicked(object sender, EventArgs e){&nbsp; &nbsp; // sender can be either a Button or a ListBox:&nbsp; &nbsp; switch (sender)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case Button button:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ProcesButtonPressed(button);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case ListBox listBox:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ProcessListBoxPressed(listBox);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break;&nbsp; &nbsp; }}这个 switch 语句对你来说可能是新的。请参阅C# 7 中的模式匹配
打开App,查看更多内容
随时随地看视频慕课网APP