Get All the Buttons In A Form including the buttons in the panel of the same form..
Asked
Active
Viewed 3.2k times
8
-
your question isn't clear enough. – Dimith Jun 21 '11 at 06:42
-
check this http://stackoverflow.com/questions/3419159/how-to-get-all-child-controls-of-a-winform-of-a-specific-type-button-textbox – V4Vendetta Jun 21 '11 at 06:47
-
You can also check this: http://stackoverflow.com/questions/253937/recursive-control-search-with-linq – Adrian Fâciu Jun 21 '11 at 06:52
3 Answers
12
List<Control> list = new List<Control>();
GetAllControl(this, list);
foreach (Control control in list)
{
if (control.GetType() == typeof(Button))
{
//all btn
}
}
private void GetAllControl(Control c , List<Control> list)
{
foreach (Control control in c.Controls)
{
list.Add(control);
if (control.GetType() == typeof(Panel))
GetAllControl(control , list);
}
}

hashi
- 2,520
- 3
- 22
- 25
5
Here is what I have done, I wrote a simple function, when I click a Button, I Select Only the Panel Control and pass it to a function for further loop through the control on that panel.
private void cmdfind_Click(object sender, EventArgs e)
{
try
{
foreach (Control control in this.Controls)
{
if (control.GetType() == typeof(Panel))
//AddToList((Panel)control); //this function pass the panel object so further processing can be done
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}

DareDevil
- 5,249
- 6
- 50
- 88
1
try this
foreach (var control in this.Controls)
{
if (control.GetType()== typeof(Button))
{
//do stuff with control in form
}
else if (control.GetType() == typeof(Panel))
{
var panel = control as Panel;
foreach (var pan in panel.Controls)
{
if (pan.GetType() == typeof(Button))
{
//do stuff with control in panel
}
}
}
}

Javed Akram
- 15,024
- 26
- 81
- 118
-
1recursion can use in case of Panel contains another panel with a button. – Nakul Chaudhary Jun 21 '11 at 07:08