如何循环遍历所有控件(包括ToolStripItems)C#
我需要保存和恢复窗体上特定控件的设置 我循环遍历所有控件并返回名称与我想要的名称匹配的控件,如下所示:如何循环遍历所有控件(包括ToolStripItems)C#,c#,controls,C#,Controls,我需要保存和恢复窗体上特定控件的设置 我循环遍历所有控件并返回名称与我想要的名称匹配的控件,如下所示: private static Control GetControlByName(string name, Control.ControlCollection Controls) { Control thisControl = null; foreach (Control c in Controls) { if (c.Name == name) { thi
private static Control GetControlByName(string name, Control.ControlCollection Controls)
{
Control thisControl = null;
foreach (Control c in Controls)
{
if (c.Name == name)
{
thisControl = c;
break;
}
if (c.Controls.Count > 0)
{
thisControl = GetControlByName(name, c.Controls);
if (thisControl != null)
{
break;
}
}
}
return thisControl;
}
由此,我可以确定控件的类型,从而确定应该/已经存储的属性
除非控件是已添加到ToolStrip中的ToolStrip族之一,否则此操作效果良好。e、 g
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lblUsername, // ToolStripLabel
this.toolStripSeparator1,
this.cbxCompany}); // ToolStripComboBox
在本例中,我可以在调试时看到我感兴趣的控件(cbxCompany),但是name属性没有值,因此代码与它不匹配
关于如何使用这些控件,有什么建议吗
干杯,
默里谢谢你们的帮助 Pinichi把我放在正确的轨道上,我在检查toolStrip.Controls-应该是toolStrip.Items 下面的代码现在非常适合我:
private static Control GetControlByName(string controlName, Control.ControlCollection parent)
{
Control c = null;
foreach (Control ctrl in parent)
{
if (ctrl.Name.Equals(controlName))
{
c = ctrl;
return c;
}
if (ctrl.GetType() == typeof(ToolStrip))
{
foreach (ToolStripItem item in ((ToolStrip)ctrl).Items)
{
if (item.Name.Equals(controlName))
{
switch (item.GetType().Name)
{
case "ToolStripComboBox":
c = ((ToolStripComboBox)item).Control;
break;
case "ToolStripTextBox":
c = ((ToolStripTextBox)item).Control;
break;
}
if (c != null)
{
break;
}
}
}
}
if (c == null)
c = GetControlByName(controlName, ctrl.Controls);
else
break;
}
return c;
}
试试这个:
//for toolstrip
if (ctrl is ToolStrip)
{
ToolStrip ts = ctrl as ToolStrip;
foreach (ToolStripItem it in ts.Items)
{
if (it is ToolStrienter code herepSeparator)
{
//-------------------------
}
else
{
//do something
}
}
}//---------------
我认为
toolStrip.Controls.Count!=toolStrip.Items.Count
。必须特别检查控件是否为ToolStrip,然后检查其项[]。