0

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

mehran
  • 13
  • 2

3 Answers3

1

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.

Palle Due
  • 5,929
  • 4
  • 17
  • 32
  • error = 'UserControl1' does not contain a definition for and no accessible extension method accepting a first argument of type 'UserControl1' could be found (are you missing a using directive or an assembly reference?) – mehran Sep 26 '19 at 09:19
  • That has nothing to do with the line I added. There must be something else wrong. – Palle Due Sep 26 '19 at 09:21
  • 'UserControl1' does not contain a definition for parent and no accessible extension method parent accepting a first argument of type 'UserControl1' could be found – mehran Sep 26 '19 at 09:25
0

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!
            }
        }
Burim Hajrizaj
  • 383
  • 4
  • 14
0

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.

anhtv13
  • 1,636
  • 4
  • 30
  • 51