【发布时间】:2010-12-22 04:55:18
【问题描述】:
我需要保存和恢复表单上特定控件的设置。
我遍历所有控件并返回名称与我想要的匹配的那个,如下所示:
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 属性没有值,因此代码与它不匹配。
关于如何使用这些控件的任何建议?
干杯, 穆雷
【问题讨论】:
-
我认为
toolStrip.Controls.Count != toolStrip.Items.Count。您必须专门检查控件是否为 ToolStrip,然后检查其 Items[]。