Take an example of a user control like this. Below user control has 1 combobox and 1 textbox.
public partial class UserControl1 : UserControl
{
ComboBox comboBox1 = new ComboBox();
TextBox textBox1 = new TextBox();
public string ComboBox1Text
{
get
{
return comboBox1.Text;
}
set
{
comboBox1.Text = value;
}
}
public string TextBox1Text
{
get
{
return textBox1.Text;
}
set
{
textBox1.Text = value;
}
}
public UserControl1()
{
InitializeComponent();
this.Controls.Add(comboBox1);
this.Controls.Add(textBox1);
}
}
In your WinForm, you can declare a List to keep track of the dynamic added User Control.
public partial class Form1 : Form
{
List<UserControl1> lst = new List<UserControl1>();
public Form1()
{
InitializeComponent();
}
}
By the time you add the user control, you add it to the List too. Example:
private void DynamicAddUserControl()
{
UserControl1 uc = new UserControl1();
panel1.Controls.Add(uc);
lst.Add(uc);
}
When you want to access value, search it within the List.
If you assume that you will only have 1 user control added dynamically, you can access it like this:
private void GetValueFromDynamicAddedUserControl()
{
UserControl1 uc = lst[0];
MessageBox.Show(uc.TextBox1Text);
MessageBox.Show(uc.ComboBox1Text);
}
If there is unpredictable number of added user control, you can loop through the List. Example:
private void GetValue()
{
foreach (UserControl1 c in lst)
{
MessageBox.Show(c.TextBox1Text);
MessageBox.Show(c.ComboBox1Text);
}
}