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

前端 未结 1 813
名媛妹妹
名媛妹妹 2020-12-20 19:28

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-bo

相关标签:
1条回答
  • 2020-12-20 19:55

    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;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题