c# 多个控件(combobox)共用同一点击事件

Posted asddasd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c# 多个控件(combobox)共用同一点击事件相关的知识,希望对你有一定的参考价值。

mark:

https://zhidao.baidu.com/question/1754127113219248788.html

https://www.cnblogs.com/gxy19fly/archive/2007/07/10/812854.html

https://www.cnblogs.com/guiqiang/p/4632667.html

 

方法一:

portComboBox1.Click += new EventHandler(refreshPort3);
portComboBox2.Click += new EventHandler(refreshPort3);
portComboBox3.Click += new EventHandler(refreshPort3);

 

private void refreshPort3(object sender, EventArgs e)
{

try
{
List<string> list = new List<string>();
string[] ports = USB.GetPorts(); //SerialPort.GetPortNames();//
if (sender == portComboBox1)
{
portComboBox1.Items.Clear();
for (int i = 0; i < ports.Length; i++)
{
portComboBox1.Items.Add(ports[i]);
}
if (ports.Length > 0)
{
portComboBox1.SelectedIndex = ports.Length - 1;
}
}
if (sender == portComboBox2)
{
portComboBox2.Items.Clear();
for (int i = 0; i < ports.Length; i++)
{
portComboBox2.Items.Add(ports[i]);
}
if (ports.Length > 0)
{
portComboBox2.SelectedIndex = ports.Length - 1;
}
}
if (sender == portComboBox3)
{
portComboBox3.Items.Clear();
for (int i = 0; i < ports.Length; i++)
{
portComboBox3.Items.Add(ports[i]);
}
if (ports.Length > 0)
{
portComboBox3.SelectedIndex = ports.Length - 1;
}
}
}
catch (Exception ex)
{
MetroMessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK);

}
}

 

 

方法二:

foreach (Control c in Panel1.Controls)
{
if (c is ComboBox)
{
c.Click += delegate (object sender, EventArgs e)
{

((ComboBox)sender).Items.Clear();
try
{
List<string> list = new List<string>();
string[] ports = USB.GetPorts(); //SerialPort.GetPortNames();//

((ComboBox)sender).Items.Clear();
for (int i = 0; i < ports.Length; i++)
{
((ComboBox)sender).Items.Add(ports[i]);
}
if (ports.Length > 0)
{
((ComboBox)sender).SelectedIndex = ports.Length - 1;
}
}
catch (Exception ex)
{
MetroMessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK);

}
};
}

}

 

以上是关于c# 多个控件(combobox)共用同一点击事件的主要内容,如果未能解决你的问题,请参考以下文章

comboboxedit控件 SelectedIndexChanged事件

c#中,如何对COMBOBOX的SelectedIndexChanged事件分别执行程序?

C# winform 下拉列表控件(comboBox)

c#多个按钮执行同一类事件-按钮按下和弹起

c#怎么用comboBox绑定treeview控件

c# comboBox控件绑定表字段问题。如何同时绑定多个comboBox呢,使其下拉列表的内容都是一样的 见详细补充