0

I have 2 listviews in tab page. however I am looking for a function to find the right control by name:

I have

foreach (Control c in form.Controls) // loop through form controls
{
    if (c is TabControl)
    {
        TabControl f = (TabControl)c;

        foreach (Control tab in f.Controls)
        {
            TabPage tabPage = (TabPage)tab;

            foreach (Control control in tabPage.Controls)
            {
                MessageBox.Show(control.Name);

                // code to go here
            }
        }     
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Moulldar
  • 63
  • 9

2 Answers2

1

The Controls collection has a Find function that returns an array:

Control[] ctrls = this.Controls.Find("listView1", true);
if (ctrls.Length == 1) {
  MessageBox.Show("Found " + ctrls[0].Name);
}
LarsTech
  • 80,625
  • 14
  • 153
  • 225
0

This will search for a control with the specified name in the controls of the specified control and all his sons.

public Control findControlbyName(String name, Control parent){
    foreach (Control ctr in parent.Controls)
    {
        if (ctr.Name.Equals(name)) return ctr;
        else return findControlbyName(name, ctr);
    }
    return null;
}

You just need to do:

findControlbyName("NameOfTheListView",this);
Aimnox
  • 895
  • 7
  • 20