如何循环遍历所有控件(包括 ToolStripItems)C#
我需要保存和恢复表单上特定控件的设置。
我循环遍历所有控件并返回名称与我想要的控件相匹配的控件,如下所示:
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 系列之一,否则这种方法效果很好。例如,
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lblUsername, // ToolStripLabel
this.toolStripSeparator1,
this.cbxCompany}); // ToolStripComboBox
在这种情况下,我可以在调试时看到我感兴趣的控件(cbxCompany),但 name 属性没有值,因此代码与其不匹配。
关于如何访问这些控件有什么建议吗?
干杯, 穆雷
I need to save and restore settings for specific controls on a form.
I loop thru all controls and return the one whose name matches the one I want, like so:
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;
}
From this I can determine the type of control and therefore the property that should be / has been stored.
This works well unless the control is one of the ToolStrip family which has been added to a toolstrip. e.g.
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lblUsername, // ToolStripLabel
this.toolStripSeparator1,
this.cbxCompany}); // ToolStripComboBox
In this case I can see the control I'm interested in (cbxCompany) when debugging, but the name property has no value so the code does not match to it.
Any suggestions on how I can get to these controls too?
Cheers,
Murray
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
谢谢你们的帮助。
Pinichi 让我走上了正确的道路,我正在检查 toolStrip.Controls - 应该是 toolStrip.Items
下面的代码现在非常适合我:
Thanks for your help guys.
Pinichi set me on the right track, I was checking toolStrip.Controls - should have been toolStrip.Items
The code below now works perfectly for me:
试试这个:
Try This: