컨트롤 이름으로 컨트롤 접근 // 변수로 컨트롤 찾기
출처
http://www.devpia.com/MAEUL/Contents/Detail.aspx?BoardID=18&MAEULNO=8&no=2027&page=2
public static class FindByNameUtil
{
public static T FindByName<T>(this object targetClass, string name) where T : class
{
System.Reflection.FieldInfo fi = targetClass.GetType().GetField(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
return fi.GetValue(targetClass) as T;
}
public static T FindByName<T>(this string name, object targetClass) where T : class
{
System.Reflection.FieldInfo fi = targetClass.GetType().GetField(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
return fi.GetValue(targetClass) as T;
}
public static System.Windows.Forms.Label Is_Label_From(this string name, object targetClass)
{
return FindByName<System.Windows.Forms.Label>(targetClass, name);
}
public static System.Windows.Forms.TextBox Is_TextBox_From(this string name, object targetClass)
{
return FindByName<System.Windows.Forms.TextBox>(targetClass, name);
}
public static System.Windows.Forms.TextBox TextBox(string name, object targetClass)
{
return FindByName<System.Windows.Forms.TextBox>(targetClass, name);
}
public static System.Windows.Forms.Label Label(string name, object targetClass)
{
return FindByName<System.Windows.Forms.Label>(targetClass, name);
}
}
사용방법
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 1; i <= 5; i++)
{
//use 1
string myControl = "label" + i.ToString();
myControl.FindByName<Label>
//use 2
Label tmp = myControl.FindByName
//use 3
this.FindByName<Label>
//use 4
("label" + i).FindByName<Label>