只有在不使用时才将串口添加到comboBox! C#

时间:2017-04-06 16:17:39

标签: c# combobox serial-port

我在不同的TabPages上有一些组合框,显示可用的串口。我可以在comboBox中选择一个端口并连接到它以获取数据。现在我希望comboBoxes隐藏已经在使用的端口。什么是最好的方法呢?

以下是组合框下拉列表中发生的事情:

    string[] portNames = SerialPort.GetPortNames();
    comboBox9.Items.Clear();
    foreach (var portName in portNames)
    {
        //checks if combox already contains same Item.
        if (!comboBox9.Items.Contains(portNames))
        {
            comboBox9.Items.Add(portName);
        }
    }




    private void button1_Click(object sender, EventArgs e)
    {
        //<-- This block ensures that no exceptions happen
        if (_serialPort1 != null && _serialPort1.IsOpen)
            _serialPort1.Close();
        if (_serialPort1 != null)
           _serialPort1.Dispose();
        //<-- End of Block

        if (comboBox2.Text != "")
        {
            _serialPort1 = new SerialPort(comboBox2.Text, BaudRate, Parity.Even, 7, StopBits.Two);       //<-- Creates new SerialPort using the name selected in the combobox
            _serialPort1.DataReceived += SerialPortOnDataReceived;       //<-- this event happens everytime when new data is received by the ComPort

            _serialPort1.Open();     //<-- make the comport listen

            button1.Enabled = false;
            button2.Enabled = true;

1 个答案:

答案 0 :(得分:1)

Change button_click event as following.

private void button1_Click(object sender, EventArgs e)
{
    //<-- This block ensures that no exceptions happen
    if (_serialPort1 != null && _serialPort1.IsOpen)
        _serialPort1.Close();
    if (_serialPort1 != null)
       _serialPort1.Dispose();
    //<-- End of Block
    // Adding port back to the comboBox as it is not open now.
    comboBox.Items.Add(_serialPort1.PortName);

    if (comboBox2.Text != "")
    {
        _serialPort1 = new SerialPort(comboBox2.Text, BaudRate, Parity.Even, 7, StopBits.Two);       //<-- Creates new SerialPort using the name selected in the combobox
        _serialPort1.DataReceived += SerialPortOnDataReceived;       //<-- this event happens everytime when new data is received by the ComPort

        _serialPort1.Open();     //<-- make the comport listen

        //removing port from the comboBox as it is now open and in-use.
        comboBox2.Items.Remove(comboBox2.Text);
        button1.Enabled = false;
        button2.Enabled = true;
 }

This should resolve your issue.