道歉,试了一下,使用foreach(control c in this.controls)应该可以访问到所有的控件,包括菜单,工具条,但是不能访问类似ImageList类的组件,这类组件需要使用 foreach(component c in this.component.Components)才可以访问. if(c as menu) 应该改成if(c is MenuStrip)
控件用foreach(control c in this.controls) 组件用foreach(Compoent c in this.compoent.components)
不行呀。 不要说 foreach(Compoent c in this.compoent.components)了 就是 for (int i = 0; i < this.components.Components.Count; i++ ) 也报错(this.components = null)。
控件用foreach(control c in this.controls) 组件用foreach(Compoent c in this.compoent.components) 无论使用this.components还是this.Controls都必须在窗体被Load之后使用,否则这两个对象都没有被初始化,在Form_Load事件中写就没有问题
{
if(c as menu)
{
//遍历
}
//操作
}
Type myType = typeof(From1); //Form1 为你的窗口类
myFieldInfo = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance
| BindingFlags.Public);
StringBuilder str = new StringBuilder();
Regex regex1 = new Regex(@"System\.Windows\.Forms");foreach (FieldInfo f in myFieldInfo)
{
if(regex1.IsMatch(f.FieldType.ToString()) == false)
continue;
str.Append(f.Name);
str.Append('\t');
str.Append(f.FieldType.ToString());
str.Append("\r\n");
}
MessageBox.Show(str.ToString());注意要引用:
using System.Text.RegularExpressions;
using System.Reflection;
foreach(component c in this.component.Components)才可以访问.
if(c as menu) 应该改成if(c is MenuStrip)
组件用foreach(Compoent c in this.compoent.components)
不要说
foreach(Compoent c in this.compoent.components)了
就是
for (int i = 0; i < this.components.Components.Count; i++ )
也报错(this.components = null)。
组件用foreach(Compoent c in this.compoent.components)
无论使用this.components还是this.Controls都必须在窗体被Load之后使用,否则这两个对象都没有被初始化,在Form_Load事件中写就没有问题
这样不需要递归(唯一不好的就是无法区分层次)
{
string feeurl = "test.aspx";
foreach(Control ctrl in container.Controls)
{
if(ctrl.HasChildren==true)//如果有子控件
{
BindDBControls(dr, ctrl);
}
else
{
if(!ctrl.Name.StartsWith("FK_"))
continue;
ctrl.Text = dr[ctrl.Name.Substring(ctrl.Name.IndexOf("_")+1, ctrl.Name.Length-ctrl.Name.IndexOf("_")-1)].ToString();
}
}//end of 1st foreach
}