【问题标题】:Can't access control state in tabcontrol pages ! C#无法访问 tabcontrol 页面中的控制状态! C#
【发布时间】:2022-11-10 17:33:48
【问题描述】:

我的项目中有一个问题,我必须在其中使用“n”个带有 tabcontrol 的用户控件。 我正在使用 Usercontrols 中存在的所有控件的名称和状态创建 txt 文件。 问题是我似乎无法访问 tabcontrol 的状态以及其中的所有控件。

我使用此命令适用于除选项卡控件之外的所有其他控件...

任何帮助将不胜感激。

sw = new StreamWriter(filename.txt);

foreach (Control crl in theformname.Controls)
{
       TabPage tab = new TabPage();
       if (crl.GetType() == tab.GetType())
                {
                    sw.WriteLine ("tabcontrol accessed");
                    if (Ctrl.GetType() == cbx.GetType())
                        {
                            CheckBox CheckBoxCrt;
                            CheckBoxCrt = (CheckBox)Ctrl;
                            sw.WriteLine(CheckBoxCrt.Checked.ToString());    //State of the checkbox
                        }
       }
}

【问题讨论】:

    标签: c# forms controls windows-forms-designer tabcontrol


    【解决方案1】:

    以下将需要在 TabControl 上方为您的 UserControl 设置一层,这将通过模仿 TabControlListCheckBoxList 来完成

    例子

    public static List<UserControlType> MyUserControlList(this Control control)
        => control.Descendants<UserControlType>().ToList();
    

    以下是在下一个代码块中使用的当前方法。

    public static class GenericExtensions
    {
        public static IEnumerable<T> Descendants<T>(this Control control) where T : class
        {
            foreach (Control child in control.Controls)
            {
                if (child is T thisControl)
                {
                    yield return (T)thisControl;
                }
    
                if (child.HasChildren)
                {
                    foreach (T descendant in Descendants<T>(child))
                    {
                        yield return descendant;
                    }
                }
            }
        }
    
        public static List<TabControl> TabControlList(this Control control)
            => control.Descendants<TabControl>().ToList();
    
        public static List<CheckBox> CheckBoxList(this Control control)
            => control.Descendants<CheckBox>().ToList();
    
    }
    

    使用 StringBuilder 的用法(请记住,您需要在 TabControl 检查上方添加一个列表),该 StringBuilder 可用于在您想要的任何位置写入,例如filename.txt

    StringBuilder builder = new StringBuilder();
    var tabs = this.TabControlList();
    
    foreach (TabControl tab in tabs)
    {
        builder.AppendLine(tab.Name);
        foreach (CheckBox box in tab.CheckBoxList())
        {
            builder.AppendLine($"	{box.Parent.Name,-20}{box.Name, -20}{box.Checked}");
        }
    }
    
    Debug.WriteLine(builder); 
    

    【讨论】:

      猜你喜欢
      • 2018-03-03
      • 2016-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-23
      • 1970-01-01
      相关资源
      最近更新 更多