How to access controls in a hosted form in a WinForm user control

In a visual studio, how do you access a control on a form, where is the user control located? For example, when the text changes in a text box in a user control, I want to change the text in another text box in another user control. Both of these user controls are placed on the same form. Thanks in advance!

+4
source share
1 answer

If you need a different user interface for data entry, I prefer to have 2 controls with a different user interface, but I will use the same data source for them and process the script using data binding.

If you bind both controls to the same data source, while you may have a different user interface, you have one information and the data of both controls are synchronized.

The answer to your question:

You can define a property in each control that sets Textto TextBox. Then you can handle the event TextChanged TextBox, and then find another control and set the text property:

Control1

public partial class MyControl1 : UserControl
{
    public MyControl1() { InitializeComponent(); }

    public string TextBox1Text
    {
        get { return this.textBox1.Text; }
        set { this.textBox1.Text = value; }
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (Parent != null)
        {
            var control1 = Parent.Controls.OfType<MyControl2>().FirstOrDefault();
            if (control1 != null && control1.TextBox1Text != this.textBox1.Text)
                control1.TextBox1Text = this.textBox1.Text;
        }
    }
}

Control2

public partial class MyControl2 : UserControl
{
    public MyControl2() { InitializeComponent(); }

    public string TextBox1Text
    {
        get { return this.textBox1.Text; }
        set { this.textBox1.Text = value; }
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (Parent != null)
        {
            var control1 = Parent.Controls.OfType<MyControl1>().FirstOrDefault();
            if (control1 != null)
                control1.TextBox1Text = this.textBox1.Text;
        }
    }
}
+1
source

All Articles