0

I have created two UserControls in my WinFroms Application. Some more UserControls will be created.

Now I want to get a list of my created UserControls by name.

For example:

UserControl ctrl1

UserControl ctrl2

UserControl ctrl3

The UserControls are created like this:

namespace Test.Controlls
{
    public partial class ctrl1 : UserControl
    {

On my WinForms Application it will be included like this:

 public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            contrctrl1.Visible = true;
            contrctrl1.BringToFront();

Now I want ot get the names ctrl1, ctrl2 and ctrl3 in a list to loop through it afterwards.

Something like this:

List<> ctrllist = new List<>();
ctrllist.Add();

for (int i =0; <ctrllist>.count; i++)
{ 
   switch (ctrllist.toString())
   {
     case "ctrl1": //do seomething
               break;
     case "ctrl2": //do seomething
               break;
     case "ctrl2": //do seomething
               break;
   }    
}

Please help me to find a solution.

Thank you.

EDIT: I don't want to know textbox, button controls etc. I have created by own UserControl "Form" and want to store these Names in a list or datatable to retreive back the names if needed.

BiSaM
  • 291
  • 1
  • 16

2 Answers2

1

Since all controls will be part of your mainform control you can get all children of that and loop through that.

Accesing Mainform.Controls (docs) likely wont be enough, you need to dig deeper. check this question on how to do that:

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

sommmen
  • 6,570
  • 2
  • 30
  • 51
  • I don't want to know textbox, button controls etc. I have created by own UserControl "Form" and whant to store these Names in a list or datatable to retreive back the names if needed. – BiSaM Apr 10 '20 at 12:26
  • okay, well what sets them apart from other controls? how are you going to find them? – sommmen Apr 10 '20 at 15:29
  • Understood, but how can I get the name of the control form the list? Ctrl1.name or ctrl.text doesn't work – BiSaM Apr 10 '20 at 16:13
1

If you want to traverse all custom controls ctrl1, you can refer to the following code.

List<ctrl1> ctrl1s = new List<ctrl1>();

private void btnGetAllCtrl_Click(object sender, EventArgs e)
{
    foreach(Control control in this.Controls)
    {
        if (control is ctrl1)
        {
            ctrl1s.Add((ctrl1)control);
        }
    }
}

And then traverse the ctrl1 list.

private void btnTraverse_Click(object sender, EventArgs e)
{
    foreach (ctrl1 c in ctrl1s)
    {
        Console.WriteLine(c.Name);
    }
}
大陸北方網友
  • 3,696
  • 3
  • 12
  • 37