Can I add a second richTextBox to my serialPort receive event?

rfresh

Active member
Joined
Aug 23, 2012
Messages
26
Programming Experience
1-3
I'm a fairly new C# programmer. I have a serialPort component I am using to 'talk' to a controller board.

I found the code example below and I am using it...it seems to be working fine. When I send a cmd to my device, what it returns is displayed in my richTextBoxReceiveWindow1 component.

What I'd like to do now, is add a second richTextBox to also receive the same data. I'm not sure how to do that?

Thank you for any help...

C#:
        private delegate void SetTextDeleg(string text);
        private void si_DataReceived(string data) { richTextBoxReceiveWindow1.Text = data.Trim(); }
        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(500);
            string data = serialPort.ReadExisting();
            // Invokes the delegate on the UI thread, and sends the data that was received to the invoked method.
            // ---- The "si_DataReceived" method will be executed on the UI thread which allows populating of the textbox.
            this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
        }
 
I discovered this worked:

C#:
private void si_DataReceived(string data) { richTextBoxReceiveWindow1.Text = data.Trim(); richTextBoxReceiveWindow2.Text = data.Trim(); }
 
I just wanted to make sure that you were looking at this the right way because your thread title indicates not.

It's not a case of adding anything to an event. The SerialPort object raises its DataReceived event and that's all it knows about. If you have registered one or more method to handle that event then those methods will be executed when the event is raised.

In your case, you've registered the 'sp_DataReceived' method to handle the event. That means that it is an event handler, not an event. An event handler is basically just a method, although it must have an appropriate signature to be able to handle any particular event. Just like any other method, you can put basically any code you want inside to be executed when the method is called.

In the case of the SerialPort.DataReceived event, it gets raised on a secondary thread. That happens so that it doesn't interfere with, or get interfered with by, anything that you're doing on the UI thread. Because of that, any changes you want to make to the UI cannot be done directly in the event handler. You must marshal a method call to the UI thread and you can then update the UI in that method. BeginInvoke is what does the marshalling.

So, once you get to your 'si_DataReceived', it is just like any other method being executed on the UI thread. Presumably you have made changes to more than one control in the same method before. This is not different at all, hence you solution looks no different to what it would have otherwise.
 

Latest posts

Back
Top Bottom