Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 374
Zach Avatar asked Mar 04 '16 18:03

Zach


1 Answers

If you need different UI for data entry, I prefer to have 2 controls with different UI, but I will use a single data source for them and handle the scenario using data-binding.

If you bind both controls to a single data source, while you can have different UI, you have a single data and both controls data are sync.

The answer to your question:

You can define a property in each control which set Text of TextBox. Then you can handle TextChanged event of the TextBox and then find the other 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;
        }
    }
}
like image 170
Reza Aghaei Avatar answered Sep 20 '22 16:09

Reza Aghaei