gpt4 book ai didi

c# - 如何遍历所有控件(包括 ToolStripItems)C#

转载 作者:行者123 更新时间:2023-11-30 16:31:54 28 4
gpt4 key购买 nike

我需要保存和恢复表单上特定控件的设置。

我遍历所有控件并返回名称与我想要的控件匹配的控件,如下所示:

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 属性没有值,因此代码与其不匹配。

关于我如何获得这些控件的任何建议?

干杯,默里

最佳答案

感谢您的帮助。

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;
}

关于c# - 如何遍历所有控件(包括 ToolStripItems)C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4506275/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com