【问题标题】:How to use an array to hold controls in form and hide/show them如何使用数组来保存表单中的控件并隐藏/显示它们
【发布时间】:2015-11-18 11:53:23
【问题描述】:

我还是个编码新手。我正在做一个计算器,但我还想要很多其他的东西。就像 c# WindowsFormsApplication 中的转换计算器、烹饪书和汉字激进字典一样

string[] numList = {"button0","button1","button2", "button3"};//this will have all number and .
for (int i = 0; i < numList.Length; i++)
{
    numList[i].Hide();
}

但它告诉我没有“隐藏”的定义,但是当我将 numList[i] 切换到 button0 时它可以工作,但我不希望每次向 comboBox 添加内容时都使用相同的 11 控件无论如何要修复这个或任何其他方法

【问题讨论】:

  • 我不明白!您正在尝试创建一个组合框,如果您单击它隐藏的项目或隐藏其他项目

标签: c# arrays winforms windows-forms-designer form-control


【解决方案1】:

如果你想隐藏所有Buttons,那么试试这个:

foreach (Button control in Controls.OfType<Button>())
{
    (control).Hide();
}

这会遍历表单的所有Buttons 并隐藏它们。但是,如果您只想隐藏特定按钮,则可以将该按钮的Tag 属性设置为OP,然后仅隐藏该Buttons

foreach (Button control in Controls.OfType<Button>())
{
     if (control.Tag.ToString() == "OP")
     {
          (control).Hide();                    
     }
}

或者使用 linq:

foreach (Button control in Controls.OfType<Button>().Where(control => control.Tag.ToString() == "OP"))
{
     (control).Hide();
}

【讨论】:

    【解决方案2】:

    试试下面的代码

    private void btnHide_Click(object sender, EventArgs e)
    {
        string[] buttonList = { "button1", "button2", "button3" };
        for (int i = 0; i < buttonList.Length; i++)
        {
            Control[] ctrl = this.Controls.Find(buttonList[i], true);
            ((Button)ctrl[0]).Visible = false;
        }
    }
    

    【讨论】:

      【解决方案3】:

      您正在保留一个字符串列表,您实际上应该将按钮添加到列表中以使 Hide 方法可见

      Control[] numList = {button0, button1, button2, button3 };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-13
        • 2016-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-24
        • 2023-04-10
        相关资源
        最近更新 更多