显示/隐藏文本框 - 可见

时间:2013-02-17 14:13:32

标签: c#

我目前正在使用文本框上的可见属性。下面我复制/粘贴了我的代码片段。在加载表单时,我总共有8个文本框设置为可见false。然后我有两个单选按钮,相应地显示文本框。一个radioButton将显示前4个文本框,另一个将显示所有8个文本框。问题是当切换回radioButton1只显示4个文本框时,它仍会显示所有8个文本框?

    private void radioButton1_CheckedChanged(object sender, EventArgs e)
    {

        int count = 0;
        int txtBoxVisible = 3;

        foreach (Control c in Controls)
        {
            if (count <= txtBoxVisible)
            {
                TextBox textBox = c as TextBox;
                if (textBox != null) textBox.Visible = true; 
                count++;
            }
        }
    }

private void radioButton2_CheckedChanged(object sender, EventArgs e)
    {

        int count = 0;
        int txtBoxVisible = 7;

        foreach (Control c in Controls)
        {
            if (count <= txtBoxVisible)
            {
                TextBox textBox = c as TextBox;
                if (textBox != null) textBox.Visible = true; 
                count++;
            }
        }
    }

2 个答案:

答案 0 :(得分:2)

尝试更改此内容:

private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
    RadioButton rb = sender as RadioButton;
    if (rb != null && rb.Checked)
    {
        int count = 0;
        int txtBoxVisible = 3;
        HideAllTextBox();
        foreach (Control c in Controls)
        {

            if(count > txtBoxVisible) break;

            TextBox textBox = c as TextBox;

            if (count <= txtBoxVisible && textBox != null)
            {
                textBox.Visible = true; 
                count++;
            }
        }
    }
}

private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
    RadioButton rb = sender as RadioButton;
    if (rb != null && rb.Checked)
    {

        foreach (Control c in Controls)
        {
            TextBox textBox = c as TextBox;
            if (textBox != null) textBox.Visible = true; 
        }
    }
}

private void HideAllTextBox()
{
    foreach (Control c in Controls)
    {
        TextBox textBox = c as TextBox;
        if (textBox != null) textBox.Visible = false; 
    }
}

在任何情况下,最好迭代控件或类似名称,以提高受影响控件的准确性

答案 1 :(得分:0)

CheckedChanged控件的Checked属性发生更改时,会发生RadioButton事件。这意味着在RadioButton被选中或未选中时。尝试写类似于:

private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
    if (radioButton1.Checked)
    {
        // Display the first 4 TextBox controls code.
    }
}

private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
    if (radioButton2.Checked)
    {
        // Display all TextBox controls code.
    }
}