Pass values from a Usercontrol to the parent Form

Asked

Viewed 42 times

0

I own a Form main and 4 UserControl with some TextBox, those UserControl is inside this Form and my intention is to take the values of the fields of these UserControl from a button on Form main, for example:

Type "Test" in some field of a UserControl and by clicking on the button on Form main outside the UserControl, I want to redeem the value of the field contained in UserControl and assign in a TextBox in the Form main this is possible?

  • YES, IT IS POSSIBLE ....

  • Can you give me an example please?

1 answer

1


Yes, it is possible.

Form 1


In the creation of their Usecontrol add a method GetText() that returns the value (property Text) of control Textbox for that method where the Form can redeem and use the information, example:

In the code of Usercontrol a GetText() that has its return from Textbox contained in the Usercontrol:

public partial class UText : UserControl
{
    public string GetText()
    {
        return TxtUText.Text;
    }
    
    public UText()
    {
        InitializeComponent();
    }

    private void UText_Load(object sender, EventArgs e)
    {
    }
}

and after adding this Usercontrol in the Form in the Button just reference the created variable of Usercontrol and the method GetText():

private void BtnOk_Click(object sender, EventArgs e)
{
    label1.Text = uText1.GetText();
}

Form 2


Form 2 consists of changing the visibility of the component contained in Usercontrol for public because it is known that all components dragged or enclosed inside Form has its visibility private by default, but select the component and in the property box modify its visibility to public as explanatory figure:

inserir a descrição da imagem aqui

in the button code the component of the Usercontrol shows the other components contained and with this possibility can also redeem their values:

private void BtnOk_Click(object sender, EventArgs e)
{
    label1.Text = uText1.TxtUText.Text;
}
  • 1

    It worked, thank you so much for your help, @novic.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.