C # using winform controls in another class

I have a WinForm application. There are several controls in the main form, such as labels, text fields, etc.

If I have another class in the same assembly, how can I access these controls?

For example, from my new class I want to update the label in Form1?

+5
source share
4 answers

In the property of the label (or any control), the parameter "Modifiers" is assigned to "Public"

Now you can access the label from the form object

 Form1 f = new Form1()
 f.lblMyLabel.Text = "My Text"
+7
source

, , /. "" ( ).

, - , ,

myForm objform = new myForm();
objform.txtName.Text="any text";

, objform.show(); objform.showdialog();

, , , , / / , .

, singleton pattern . , , , , .

, , , , ,

+3

Form1, , .

, Label label1 , - :

public Label MyForm1Label { get { return label1; } }
+2
source

In addition to the solutions already mentioned, you can create some public method on your Form that will provide the required functionality (maybe it’s good if some changes should be displayed in several controls - your other classes should not remember which one to change)

public void SetSomething(int value)
{
   Control1.value = value;
   Control2.value = value;
   ...
}
+1
source

All Articles