WinForm开发中几种找控件的方法
#region 在当前控件集中查找ToolStripButton
private static ToolStripButton FindToolStripButton(Form owner, string controlId)
{
ToolStripButton result;
result = null;
foreach (Control ctl in owner.Controls)
{
if (ctl.GetType() == typeof(System.Windows.Forms.ToolStrip))
{
ToolStrip ts = ctl as ToolStrip;
ToolStripItem[] items = ts.Items.Find(controlId, true);
if (items.Length > 0)
{
result = (ToolStripButton)items[0];
return result;
}
}
}
return result;
}
#endregion
//Form中直接找
Control[] ctls = owner.Controls.Find(dr["ControlName"].ToString(), true);
//Form的Components中找控件
ArrayList myList = owner.GetIntfObjects(typeof(IFindContainer));
for (int i = 0; i < myList.Count; i++)
{
if(myList[i] is DataSet)
{}
}
public ArrayList GetIntfObjects(Type intfType)
{
ArrayList aRet = new ArrayList();
ReflectionPermission reflectionPerm1 = new ReflectionPermission(PermissionState.None);
reflectionPerm1.Flags = ReflectionPermissionFlag.AllFlags;
if (intfType.IsInterface)
{
Type type = this.GetType();
FieldInfo[] myFields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
for (int i = 0; i < myFields.Length; i++)
{
object newobj = myFields[i].GetValue(this);
if ((null != newobj) && (null != newobj.GetType().GetInterface(intfType.Name)))
{
aRet.Add(newobj);
}
}
}
return aRet;
}