C# using winform controls in another class

2020-02-14 02:26发布

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?

5条回答
够拽才男人
2楼-- · 2020-02-14 03:07

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

 Form1 f = new Form1()
 f.lblMyLabel.Text = "My Text"
查看更多
做自己的国王
3楼-- · 2020-02-14 03:13

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

查看更多
一纸荒年 Trace。
4楼-- · 2020-02-14 03:14

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

查看更多
我想做一个坏孩纸
5楼-- · 2020-02-14 03:22

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; } }
查看更多
▲ chillily
6楼-- · 2020-02-14 03:32

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;
   ...
}
查看更多
登录 后发表回答