views:

392

answers:

4

How to access the controls of form2 in form1

And also I would like to create events for form2 controls in form1 itself. How to acheive this? Please help me with complete code using C#2008, Windows Forms.

A: 

Open form 2 from within form 1, and use the variable you open it with to access the form.eg.

In Form 1

Form2 secondForm = new Form2();
Form2.Show();

secondForm.somePublicControl.Text = "test";
MessageBox.Show(secondForm.somePublicVariable);
LnDCobra
First of all i'm unable to access the secondform.<Controls>Unable to access controls of the secondform.
sukumar
what error message? Are you sure the second forms controls are public or inherit modifiers (and not private?) and also make sure you have called the InitialiseComponent in the second form, before trying to access a control on that form.
LnDCobra
A: 

Do you really want to access the controls in different forms or do you want to react to value changes to data used in another form? The latter case can be implemented by binding controls to global model data and using INotifyPropertyChanged interface to signal/listen for data changes.

Andre van Heerwaarde
A: 

Ok, so lets say you have frmMain and frmSettings. You want frmSettings to update, say, a label on frmMain. Here's how I'd go about it.

Step 1. In your frmMain.Designer.cs change the labels(or other controls) scope to public.

Example.

public System.Windows.Forms.GroupBox groupBox2;
public System.Windows.Forms.Label label8;

Now that was easy eh?

Step 2. In your frmSettings declare this.

protected frmMain frmMain;

    public frmSettings(frmMain frmMain)
    {
        this.frmMain = frmMain;
    }

Now just have fun changing things. Like:

frmMain.label8.Text="Changed from frmSettings";
Dremation
A: 

The best practice wants you to set properties of those controls attributes you want to expose so that no one can really interfere with your form's desired behaviour.

public partial class SecondaryForm {
    // Let's suppose you have put a TextBox control in design mode named txtCusomerName.
    public string CustomerName {
        set {
            this.txtCustomerName.Text = value.Trim();
        }
    }
}

public partial class MainForm {
    // Suppose you have a button to show a form with the customer name.
    private btnShowCustomerName_Click(object sender, EventArgs e) {
        SecondaryForm f
        f.CustomerName = "Acme inc,";
        f.ShowDialog();
    }
}

Does this help?

Will Marcouiller