mehran
mehran

Reputation: 19

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

Upvotes: 0

Views: 1388

Answers (3)

anhtv13
anhtv13

Reputation: 1808

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.

Upvotes: 0

Palle Due
Palle Due

Reputation: 6292

You are creating a new Form1. You are not showing it. You probably meant to update an existing Form1. I suppose the UserControl1 is placed on the Form1. Then you can do this:

private void button1_Click(object sender, EventArgs e)
{
    // Get the parent form
    Form1 myForm = (Form1) this.parent;
    myForm.TextBox1.Text = "1";
}

If your UserControl1 is not on Form1, then you need to pass a reference somehow.

Upvotes: 1

Burim Hajrizaj
Burim Hajrizaj

Reputation: 381

remove the row where you create a new Form

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

                //The textbox text is not updated!
            }
        }

Upvotes: 0

Related Questions