0

I have a problem with my C# Windows Form App, i'm trying to change the active tab in tabControl1, it works when I click on the button1 but when I send serial data, the page change, but the program crashes.
The serial data is sent by an Arduino, it only send "S" every 2 seconds.

Here is the code I used to test this :

public partial class Form1 : Form
{
    int page = 0;
    public Form1()
    {
        InitializeComponent();
        serialPort1.Open();
    }

    private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        page++;
        if (page == 4)
        {
            page = 0;
        }
        tabControl1.SelectedIndex = page;
        tabControl1.Refresh();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        page++;
        if (page == 4)
        {
            page = 0;
        }
        tabControl1.SelectedIndex = page;
        tabControl1.Refresh();
    }
}    

Is this a bug, or am I doing it the wrong way ?

LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • 2
    related, assuming the *crash* is due to a cross-thread exception: https://stackoverflow.com/questions/661561/how-do-i-update-the-gui-from-another-thread/661662#661662 – rene May 21 '18 at 13:53
  • 1
    what's the error when it crashes? A crash could be caused by any number of things...to help better we'd need to know the details of the exception. – ADyson May 21 '18 at 13:53
  • 1
    There is no error code, the app just freeze and "The application has stopped working" – Tommy Puiroud May 21 '18 at 14:00
  • 3
    Will you remove the edit and write it as an answer please. I came to answer the question, assuming it was still open, and realized you already fixed it. – Michael Puckett II May 21 '18 at 14:37
  • 1
    "the app just freeze" Hopefully in that scenario there'd be something more detailed logged in the Windows Event Viewer – ADyson May 21 '18 at 14:39

1 Answers1

0

The DataReceived event is raised on a secondary thread when data is received from the SerialPort object.

https://msdn.microsoft.com/fi-fi/library/system.io.ports.serialport.datareceived(v=vs.110).aspx

you have to use invoke method to modify the form main thread UI elements.

//Create a delegate     
public delegate void ModifyTabPage();

//Create an object in the form for delegate and instatiate with the method which modifies tabpage
public ModifyTabPage myDelegate;
myDelegate = new ModifyTabPage(ModifyTabPageMethod);


public void ModifyTabPageMethod()
{
        page++;
        if (page == 4)
        {
            page = 0;
        }
        tabControl1.SelectedIndex = page;
        tabControl1.Refresh();
}



//using invoke access it from the data recived event of your serialize port.    
myFormControl1.Invoke(myFormControl1.myDelegate);

This Should work.

Pavan Chandaka
  • 11,671
  • 5
  • 26
  • 34