I am using this piece of code to find serial ports and show their names in combobox.
string[] ports = SerialPort.GetPortNames();
foreach (string p in ports)
{
comboBox1.Items.Add(p);
}
comboBox1.SelectedIndex = 0;
So, when I start my program, the default port should be the first from the ports
I am using this function to initialize serial port
private void portInit()
{
port.PortName = comboBox1.Text;
port.BaudRate = 57600;
port.Parity = Parity.None;
port.ReceivedBytesThreshold = 8;
port.DataBits = 8;
port.Handshake = Handshake.None;
port.StopBits = StopBits.One;
port.DataReceived += new SerialDataReceivedEventHandler(datarecievedhandler);
port.Open();
}
I have this event handler if the user decides to change serial port
private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
port.Close();
port.PortName = comboBox1.Text;
port.Open();
}
I intialize my serial port in this part of code
public Form1()
{
InitializeComponent();
InitializeGraphs();
portInit();
if (port.IsOpen)
textBox1.Text += "-Port " + port.PortName + " is opened\r\n";
}
The device is connected to the first(default) serial port. When I run my program, the first port opens(I know that it opens because of the textbox), but the datarecieved event handler doesnt work. When I change serial port in combobox, nothing happens(expected behaviour), and when I change my serial port back to the first one, it opens, and the datarecieved event handler works fine. Of course, I want the first serial port to work instantly, without changeing serial ports. I know this question is a long shot, but maybe someone had the similar problem.