C# – How to Get Data From User Control on Form

cformsuser-controls

I'm building a simple app in Visual Studio 2010 using C#, and I'm doing this to get familiar with user control because it seems to make it easier than creating multiple forms.

On the main form, there is a dropdown list the contains 2 values, "UCType1" and "UCType2". I created 2 different user controls. I was using panel on the main form to display the user control according to what they selected in the dropdown list.

I was able to display the appropriate user control based on the user selection, but now I ran into some issue. I couldn't get the main form to read data from the user control.

Let's say there is a button "Execute" and a label "Warning" on the main form. There is a textbox "Name" on the user control.

The scenario is: when the user hit "Execute", if "Name" is blank, "Warning" will display some error message.

I was trying to use if(UserControl1.Name.Text == "") on the main form but I couldn't even reference it like that.

I know I can just create separate forms to make it easier since that will make all variable in the same file, but I want to know if there's a way to do it with user control because I would like to get familiar with it.

Thanks

This is how I display my user control

private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    UCType1 uc1 = new UCType1();
    panel1.Controls.Clear();
    panel1.Controls.Add(uc1);
}

and when I was trying to display the data from user control

private void executeButton_Click(object sender, EventArgs e)
{
    UCType1 uc1 = new UCType1();
    warning.Text = uc1.Name;
}

nothing was happening.

Best Answer

Create one public property in UserControl which set or get TextBox text. Like

    public String Name
    {
        get { return textBox1.Text;  }
        set { textBox1.Text = value; }
    }

Now you can access Name from your Form. like :

if(UserControl1.Name == "")