【问题标题】:How should I change the visibility of a TextBox when a ComboBox value changes?当 ComboBox 值更改时,我应该如何更改 TextBox 的可见性?
【发布时间】:2015-03-12 22:51:43
【问题描述】:

我是编程新手,我正在尝试根据组合框上的选定值更改文本框的值,因为值是数字 1 到 20,并且根据选择,它将是数字可见的文本框。我正在使用已更改的事件选择索引。

这是我的代码:

private void cbxPIN_SelectedIndexChanged(object sender, EventArgs e)
{
    int pines = Convert.ToInt32(cbxPIN.SelectedItem.ToString());
    if (pines == 1)
    {
        textbox1.visible = true;
    }
    else if (pines == 2)
    {
        textbox1.visible = true;
        textbox2.visible = true;
    }
 ...

    else if (pines == n)
    {
        textbox1.visible = true;
        textbox2.visible = true;
 ...
        textboxn.visible = true;
    }
}

既然组合框上有 25 个不同的数值,是否有更简单的方法来执行此操作?除了比较每个不同的值吗?

类似循环的东西。

【问题讨论】:

    标签: c# winforms combobox textbox


    【解决方案1】:

    至少,我会这样重写它,以减少重复:

    private void cbxPIN_SelectedIndexChanged(object sender, EventArgs e)
    {
        int pines = Convert.ToInt32(cbxPIN.SelectedItem.ToString());
    
        if (pines >= 1)
            textbox1.Visible = true;
    
        if (pines >= 2)
            textbox2.Visible = true;
    
        ...
    
        if (pines >= n)
            textboxn.Visible = true;
    }
    

    实际上,我会将所有TextBox 控件添加到集合中,可能在构造函数中:

    List<TextBox> TextBoxes = new List<TextBox> { textbox1, textbox2, ... textboxn };
    

    然后使用 LINQ 的 Take() 方法获取第一个 xx 个控件并遍历它们:

    foreach (var tb in TextBoxes.Take(pines))
        textBox.Show();
    

    【讨论】:

      【解决方案2】:

      您想使用循环结构。您应该验证要执行的循环数 > 0 并且

      private void cbxPIN_SelectedIndexChanged(object sender, EventArgs e)
      {
          int pines = Convert.ToInt32(cbxPIN.SelectedItem.ToString());
          TextBox textBox;
          for (int i = 1; i <= pines; i++)
          {
              // get the control from the form's controls collection by the control name
              textBox = this.Controls["textbox" + pines.ToString()] As TextBox
              textBox.Visible = true;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2013-11-30
        • 1970-01-01
        • 2019-11-07
        • 2016-11-02
        • 1970-01-01
        • 2021-03-12
        • 1970-01-01
        • 1970-01-01
        • 2012-08-22
        相关资源
        最近更新 更多