Search code examples
c#winformsuser-controls

Pass value from Usercontrol to Form


I create a usercontrol1 with textBox. And with my form I add a usercontrol(the usercontrol1 with textBox) and a textBox. I already know how to pass value from Form to Usercontrol.

Form Code
public string ID
    {
        get { return textBox1.Text; }
    }
private void textBox1_TextChanged(object sender, EventArgs e)
    {
        userControl11.ID = ID;
    }

Usercontrol Code
public string BorrowerID
    {
        set { textBox1.Text = value; }
    }

But don't know how to pass the value from textBox of Usercontrol to textbox of Form? I found on how to close the form from usercontrol.

((Form)this.TopLevelControl).Close();

Change parentform color

this.ParentForm.BackColor= Color.Red;

How would i implement something like this or other method to pass value from usercontrol to form?

((Form)this.TopLevelControl).ID = ID;

or

this.ParentForm.ID= ID;

Solution

  • I create the UserControl1 in a new project and reference it to my project that contains the form instead of directly adding UserControl in the form´s project, that's why things get complicated.

    Here it now to pass value from UserControl to Form

    UserControl

    public string ID2
    {
        get { return textBox1.Text; }
    }
    
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        var textBoxContent = this.textBox1.Text;
        var parent = this.Parent as Form1;
        parent.ID2 = ID2;  
    }
    

    Form1

    public string ID2
    {
        set { textBox1.Text = value; }
    }