Search code examples
c#serial-porttabcontroltabpage

How to pragmatically select tabPage2 of tabControl1 in C# in serialPort1 receiveData event?


I have a serialPort1 object to receive data from RS232 port. I want to select tabPage2 of tabControl1 when "finish" as a string comes from RS232. This code is what I want to do.

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            RxString = serialPort1.ReadExisting();

            if(RxString == "finish")
            {
                tabControl1.SelectedIndex = 1;
            }

            this.Invoke(new EventHandler(DisplayText));
        }

When I use "tabControl1.SelectedIndex = 1;" in a button event, when I click on button it works very well but when I put it in "serialPort_DataReceived" event it shows me an error:

The error is: "Cross-thread operation not valid: Control 'tabControl1' accessed from a thread other than the thread it was created on."


Solution

  • serialPort1_DataReceived occurs in a secondary thread other than you main thread. You need to use a delegate to perform such cross-thread operation. Here is a sample code to get the idea-

    // This delegate enables asynchronous calls
    delegate void SetIndexCallback(string text);
    
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
    
        if (this.tabControl1.InvokeRequired)
        {   
                SetIndexCallback d = new SetIndexCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            tabControl1.SelectedIndex = int(text);
        }
    }