Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Change the properties of controls from another form

Status
Not open for further replies.

jpreciado

MIS
Feb 7, 2004
36
MX
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.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top