Search code examples
c#eventsserial-porthandler

Changing textBox.text from event handler


Can't seem to find an answer here for the life of me.. Anyhow, how can an event handler change Form's textBox.text?

private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();
            //Do what ever you want with the data
            textBox2.Text = "test"; //alas, this doesn't work
        }

The event handler is created when a button is pressed

private void button3_Click(object sender, EventArgs e)
        {
                    serialPort1.PortName = comboBox1.Text;
                    serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
                    serialPort1.RtsEnable = true;
                    serialPort1.DtrEnable = true;
                    serialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                    serialPort1.Open();
                }
            }

Any help is greatly appreciated


Solution

  • The DataReceivedHandler method is marked static, so it cannot access the instance member textBox2. Does removing static solve the problem?