简体   繁体   中英

C# using winform controls in another class

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) set the "Modifiers" option to "Public"

Now you can access the label from the object of the Form

 Form1 f = new Form1()
 f.lblMyLabel.Text = "My Text"

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

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

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:

public Label MyForm1Label { get { return label1; } }

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM