Question

when i create a control by drag and drop VS automatically generate code like this:

public System.Windows.Forms.Label label1;

When i want to change modifier of that control to Static, i go to Form1.Designer.cs and edit to:

public static System.Windows.Forms.Label label1;

It's ok. But when i modify every control, VS automatically change it to origin :(. So how do you change modify of a control to static ?

sorry, im bad at English :(


code from a comment:

public static void setLabelInfoVisible(bool visible) 
{ 
   if (Form1.labelInfo.InvokeRequired) 
   { 
      setLabelInfoVisibleDelegate del =
         new setLabelInfoVisibleDelegate(setLabelInfoVisible);
      Form1.labelInfo.Invoke(del, new object[] { visible }); 
   } 
   else 
   { 
     Form1.labelInfo.Visible = visible; 
   } 
}
Was it helpful?

Solution

Designer code is not supposed to be user modified, as it gets re-written by Visual Studio every time you make changes to your form in the designer (as you have discovered).

One way forward it to move the control declaration and initialization to the non designer code file. However, that means your control will no longer appear in the designer.

Edit: This is not the way to make your controls accessible to other threads! I can't think of a valid reason to make the control static.

OTHER TIPS

It seems that your actual problem is another one: Updating controls from another thread. This should NOT be accomplished by static controls!

These related questions should solve your problem:

How to update textbox on GUI from another thread in c#

How to update GUI from another thread in C#?

Wayne,

  1. No, you don't want a Control to be static. Explain why you think you do and we can find out what the better alternatives are.

  2. Don't edit in *.Designer.cs files. The tools (Forms/Dataset/... designers) have the right to overwrite everything.

Edit:

You have 2 problems to solve,

  1. Accessing the Control from another class. This should be done by passing an instance-reference to that other class. Something like:
    void Form1_Load(..) { otherObject.Form = this; }

  2. Using the Control form another thread. You can never do so directly, always use Control.Invoke(). Divo lists 2 useful links.

You'll have to move the definition out of the autogenerated designer code, from the file Form.Designer.cs to your code Form.cs.

Perhaps you could create a new class that inherits the control in question, and then apply the singleton pattern to it.

That way you have a global (thread safe) point of access to it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top