من یک تابع نوشتم که خودم خیلی ازش استفاده می کنم برای شما هم می زارم هم برای این کاری که می خواین به درد می خوره هم شاید به درد بقیه بخوره
public static bool IsKindOfType(Type Type, Type BaseType)
{
Type CounterType = Type;
while (CounterType != null)
{
if (CounterType == BaseType)
return true;
CounterType = CounterType.BaseType;
}
Type[] allInterfaces = Type.GetInterfaces();
foreach (Type InType in allInterfaces)
if (InType == BaseType)
return true;
return false;
}
public static List<Control> GetAllSubControls(Control Ctl, params Type[] BaseTypes)
{
if (BaseTypes == null || BaseTypes.Length == 0)
BaseTypes = new Type[1];
for (int i = 0; i < BaseTypes.Length; i++)
if (BaseTypes[i] == null)
BaseTypes[i] = typeof(Control);
List<Control> lstCont = new List<Control>();
foreach (Control x in Ctl.Controls)
lstCont.Add(x);
for (int i = 0; i < lstCont.Count; i++)
foreach (Control x in lstCont[i].Controls)
lstCont.Add(x);
for (int i = lstCont.Count - 1; i >= 0; i--)
{
bool blnOk = false;
foreach (Type BType in BaseTypes)
if (IsKindOfType(lstCont[i].GetType(), BType))
{
blnOk = true;
break;
}
if (!blnOk)
lstCont.RemoveAt(i);
}
return lstCont;
}
تابع IsKindOfType رو شما مستقیما احتیاج ندارید بلکه برای کارتون از تابع GetAllSubControls استفاده کنید
نحوه کارشم اینجوریه:
مثلا فرض کنید می خواید همه Label های یک فرم رو بارگذاری کنید:
تابع رو اینحوری باید براخوانی کنید:
List<Control> lstLable = GetAllSubControls(this, typeof(Label));
foreach (Control lbl in lstLable)
lbl.Enabled = false;
با این کد هر چی label توی فرمتون باشه توی یک لیست قرار می گیره(حتی اگر داخت یک panel یا هر چیز دیگه باشه)
حالا مثلا فرض کنید می خواید تمام TextBox ها و Button های فرمتون رو برگردانید کافیه تابع رو اینجوری فراخونی کنید:
List<Control> lstControl = GetAllSubControls(this, typeof(TextBox), typeof(Button));
ضمنا می تونید به جای this یک پنل رو قرار بدین که در این صورت فقط کنترل های داخل اون پنل بر گردانده می شوند
امیدوارم بدردتون بخوره