In C#, I need to change the properties of controls on another form. For example, with a label control on Form 1, how can I change its text property from Form 2?
There are a few options. Some are easy, some are a pain. Here's 2 ideas for you:
1. Register your Form1 with Form2.
private Form1 myForm1
public Form2(Form1 pform)
{
InitializeComponents();
myForm1 = pform; //Set the local variable myForm1
//In form 2 to the calling code.
}
Then you can access functions and properties on your Form1. You might have to make the controls that you want to modify public. (public System.Windows.Form label1)
This is usually a BAD IDEA though. You are externally changing properties that should be private.
2. Have your Form2 throw events.
public event EventHandler UpdateLabelInfo;
Then in your form1 you would say:
private void button1_Click(object sender, eventargs e)
{
Form2 myForm2 = new Form2();
myForm2.UpdateLabelInfo += new EventHandler(myForm2_UpdateLabelInfo());
}
private void myForm2_UpdateLabelInfo()
{
//Set your properties in Form1
}
3. This is probably the best option. It works off a design pattern called "Model-View-Controller"
Basically, create a controlling class that handles all interaction between forms.
AppController myApp = new AppController();
myApp.SetForm1Label();
This would allow you to change the properties of Form1 from any form or control that has access to AppController.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.