简体   繁体   English

当ComboBox值更改时,如何更改TextBox的可见性?

[英]How should I change the visibility of a TextBox when a ComboBox value changes?

I'm new to programming and I'm trying to change the value of a textbox depending of a selected value on a combo box, since the values are numerical 1 to 20, and depending on the selection it will be the number of text boxes visible. 我是编程新手,我想根据组合框上的选定值来更改文本框的值,因为这些值是1到20的数字,并且取决于选择,它将是文本框的数量可见。 I'm using the event selected index changed. 我正在使用所选索引已更改的事件。

Here is my code: 这是我的代码:

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

since there are like 25 different numeric values on the combo box is there an easier way of doing this? 由于组合框上有大约25个不同的数值,是否有更简单的方法? asides from comparing each different value? 从每个不同的值进行比较?

Something like a loop. 有点像循环。

At the least, I'd rewrite it like this, to reduce duplication: 至少,我会这样重写它,以减少重复:

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

Actually, I'd add all the TextBox controls to a collection, possibly in the constructor: 实际上,我会将所有TextBox控件添加到集合中,可能在构造函数中:

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

Then use LINQ's Take() method to grab the first xx number of controls and iterate through them: 然后使用LINQ的Take()方法来获取前xx个控件并对其进行遍历:

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

You want to use a loop structure. 您要使用循环结构。 You should validate that the number of loops to perform is > 0 and < the number of textboxes you have available, but I'll leave error handling to you. 您应该验证要执行的循环数> 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM