Here is some code you can use, in this code I compare the control by the control type but if you want you can change is to compare by the control name and it works effectively.
private void button1_Click(object sender, EventArgs e)
{
object childgrid;
childgrid = getControlByType(this, typeof(DataGridView).ToString());
childgrid = getControlByName(this, dataGridView1.Name);
}
private object getControlByType(Control Main, string controlType)
{
if (Main.HasChildren)
{
foreach (var control in Main.Controls)
{
if (control.GetType().ToString() == controlType) return control;
}
}
return null;
}
private object getControlByName(Control Main, string controlName)
{
if (Main.HasChildren)
{
foreach (var control in Main.Controls)
{
var ctl = (Control) control;
object ctl2 = null;
if (ctl.GetType().ToString() == typeof (DataGridView).ToString())
{
ctl2 = ctl;
if (ctl.Name == controlName)
{return ctl2;}
ctl2 = null;
}
if (ctl.GetType().ToString() == typeof(Button).ToString())
{
ctl2 = ctl;
if (ctl.Name == controlName)
{ return ctl2; }
ctl2 = null;
}
if (ctl.HasChildren)
{
ctl2 = getControlByName(ctl, controlName);
}
if (ctl2 != null)
return ctl2;
}
}
return null;
}