使用C#限制组合框中端口名称的重复

时间:2017-02-07 05:53:57

标签: c#

每次时钟滴答时,我都会使用comboBox.Items.AddRange(条目)将项目添加到组合框中。

但是如何避免在组合框中重复输入(即同名条目)。我试过这段代码

        string[] ports = SerialPort.GetPortNames();

        if (!comboBox1.Items.Contains(ports.ToString()))
        {
            comboBox1.Items.Add(ports.ToString());
        }

我不知道为什么显示System.String[]

1 个答案:

答案 0 :(得分:0)

它显示System.String[]因为SerialPort.GetPortNames()返回数组中的多个字符串,而不只是一个字符串。

您需要浏览数组中的每个项目,并为每个项目运行Contains()Add()

string[] ports = SerialPort.GetPortNames();
foreach(var p in ports) // Go through each string in the array
{
  if (!comboBox1.Items.Contains(p))
    comboBox1.Items.Add(p);
}