Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need to update windows form controls data from Static method. we cannot access controls from static method because they are instance fields.then how to over come this.

C#
private static void DataReceivedHandler(
                       object sender,
                       SerialDataReceivedEventArgs e)
       {
           SerialPort sp = (SerialPort)sender;
           //Thread.Sleep(1000);
           string indata = sp.ReadExisting();


        
           lblID.Text = indata;
           if (lstRFIDCards.Contains(indata))
           {
               lblIDValidationMes.Text = "ID Verified";
               lblIDValidationMes.ForeColor = System.Drawing.Color.Green;

               byte[] onBuffer = { 0XA5, 0XFF, 0X04, 0X57, 0X0F, 0X01, 0XF0, 0x0D, 0x0A };
               sp.Write(onBuffer, 0, 9);
               lblRelay.Text = "Relay ON";
              lblRelay.ForeColor = System.Drawing.Color.Green;
               Thread.Sleep(5000);
               //MessageBox.Show(indata);
               byte[] offbuffer = { 0xA5, 0xFF, 0x04, 0x57, 0x0F, 0x00, 0xF1, 0x0D, 0x0A };
               sp.Write(offbuffer, 0, 9);
              lblRelay.Text = "Relay OFF";
              lblRelay.ForeColor = System.Drawing.Color.OrangeRed;

           }
           else
           {
              lblIDValidationMes.Text = "ID Not Matched Our Records.";
              lblIDValidationMes.ForeColor = System.Drawing.Color.OrangeRed; ;
           }



       }
Posted
Updated 17-Jun-15 22:54pm
v4

1 solution

The only way in practice to overcome this is: don't use a static method.

You can bodge round it by creating a static Form variable and loading it with your form instance, but it is just that: a bodge. And as soon as you have two instances of the form it all falls apart.

So look at why you need a static method, and check that you really do need a static handler: I doubt if you do in practice. And please, do remember that the DataReceived event handler is not executed on the UI thread - you will need to Invoke any controls you want to access to avoid cross thread problems.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900