开发者

How to access the controls of form2 in form1 in C# 2008/2010

开发者 https://www.devze.com 2022-12-24 06:43 出处:网络
How to acc开发者_运维百科ess the controls of form2 in form1 And also I would like to create events for form2 controls in form1 itself. How to acheive this?

How to acc开发者_运维百科ess 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.


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";


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?


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);


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.


What helped me today is Call Form 1, Form 2 Function:

f2 frm = new f2();
frm.ShowDialog(this);
MessageBox.Show(frm.proc); // frm.proc is variable public in Form2
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号