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

一笑奈何 提交于 2019-12-19 19:59:34

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/35803785/how-to-access-controls-on-hosted-form-in-a-user-control-winform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!