I have a WinForm application. On the main form there are a number of controls, such as labels, textboxes, etc.
If I have another class, within the same assembly, how can I access those controls?
For example from my new class, I want to update a label in Form1?
In the property of the label (or any control) make the "Modifiers" option to "Public"
Now you can access the label from the object of the Form
The easyiest way is to use:
Form1 f = new Form1() f.lblMyLabel.Text = "My Text"
Therefore, you have to set the Form1 Label "lblMyLabel" just to public. I have done it with a richTextBox.
enter image description here
select the control which you wants to access from another class/form. go to its property and set its modifiers value to "internal" (if you want to use it only in same assembly) .
now where ever in same assembly you wants to use it just create an object of that form like
then you can show that form using objform.show(); or objform.showdialog();
but i think this will not solve you issue because what i feel is that your form is already showing on screen and from another form/class you wants to change its label/textbox's value so for this you will have to take that current object of form otherwise it will not show any changes on currently showing form.
so i think singleton pattern will give you perfect solution. just create class and in that class create a static object of that form and than create a static function and check if object is already initialized that do not initialize it and use existing otherwise initialize it.
there are lots of other solutions also exists like by creating public property but you will have to use reference of same object of currently showing form to see changes reflect to currently showing form
One way would be to create public properties in your Form1 class that expose the controls you are trying to modify
For example, if your Label is called label1 in the designer then you could do something like this:
Apart from the solutions which were already mentioned you can create some public method to your Form that will provide desired functionality (Might be good if some change has to be displayed in several controls - your other classes don't have to remember which one to change)