0

我目前正在使用文本框上的可见属性。下面我复制/粘贴了我的代码片段。加载表单时,我总共有 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++;
            }
        }
    }
4

2 回答 2

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

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

于 2013-02-17T14:18:05.240 回答
0

当控件的属性发生变化时发生该CheckedChanged事件。这意味着无论是选中还是未选中。CheckedRadioButtonRadioButton

尝试编写类似于以下内容的内容:

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.
    }
}
于 2013-02-17T14:20:49.073 回答