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