Search code examples
c#winformsuser-controls

How to update the label text in the form with usercontrol?


I put a button inside UserControl and put this UserControl in the form. I want the textbox text in the form to be updated when the button is clicked.

public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Form1 form1 = new Form1();
            form1.textBox1.Text = "1";

            //The textbox text is not updated!
        }
    }

The textbox text is not updated


Solution

  • Don't create a new Form. Please remove that line.

    I guess you are trying to set text for a TextBox in Form and your button is in Usercontrol which is child component of the Form.

    If so please register an EventHandler from your Form and fire event from your Button in UserControl.

    Register an EventHandler in your UserControl:

    public event EventHandler ButtonClicked;
    protected virtual void OnButtonClicked(EventArgs e)
    {
        var handler = ButtonClicked;
        if (handler != null)
            handler(this, e);
    }
    private void Button_Click(object sender, EventArgs e)
    {        
        OnButtonClicked(e);
    }
    

    In your Form, you subscribe the event from UserControl:

    this.userControl1.ButtonClicked += userControl11_ButtonClicked;
    
    private void userControl11_ButtonClicked(object sender, EventArgs e)
    {
        this.TextBox1.Text = "1";
    }
    

    Let me know your result.