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);

}
};
}

}

 

上一篇:Nano pi/树莓派及arm架构,Ubuntu下找不到包问题


下一篇:go build