How to get data from user form control

I am creating a simple application in Visual Studio 2010 using C #, and I am doing this to get to know a user control, because it makes it easier to create multiple forms.

In the main form, there is a drop-down list containing 2 values, " UCType1" and " UCType2". I created two different user controls. I used the panel in the main form to display the user control according to what they selected in the drop-down list.

I was able to display the corresponding user control based on user selection, but now I am facing some kind of problem. I could not get the main form for reading data from a user control.

Let's say there is a button " Execute" and a label " Warning" in the main form. The user element has a text field " Name".

Scenario: when the user clicks " Execute", if " Name" is empty, " Warning" will display some error message.

I tried to use if(UserControl1.Name.Text == "")in the main form, but I could not even refer to it.

I know that I can simply create separate forms to simplify, as this will make the whole variable in one file, but I want to know if there is a way to do this with a user control, because I would like to familiarize myself with it.

thank

This is how I show 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 tried to display data from a user control

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

nothing happened.

+3
source share
2 answers

Create one public property in UserControlthat sets or receives text TextBox. how

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

Now you can access the name from your form. eg:

if(UserControl1.Name == "")
+5
source

You have a problem with the code, you are creating the control object again, and not using the existing control object

UCClientType1 uc1 = new UCClientType1();//access exsting object do not create new
warning.Text = uc1.Name;

serach , ,

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

shoudl

private void executeButton_Click(object sender, EventArgs e)
{
    UCClientType1  uc =frm.panel1.Controls.FindControl("uc1",true) as UCClientType1;
    if(uc1 != null)
    warning.Text = uc1.Name;
}

,

Form parentForm = (this.Parent as Form);
var data = parentForm.textbox1.Text;

, usercontrol mainform,

 UserControl uc =frm.Controls.FindControl("myusercontrol",true);
 from.warning.Text = uc.Textbox1.Text;
+1

All Articles