2013-02-17 90 views
0

我目前正在使用文本框上的可见属性。下面我复制/粘贴我的代码片段。当窗体被加载时,我总共有8个文本框设置为可见错误。然后我有两个单选按钮相应地显示文本框。一个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

尝试修改此:

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

在任何情况下,它会更好,通过控制或类似的名称进行迭代,对受影响的控制

+0

当我回去,只显示4个文本框,它仍然显示8? – CodingWonders90 2013-02-17 14:54:10

+0

更新!添加了HideAllTextBox方法 – Mate 2013-02-17 14:57:04

0

CheckedChanged事件occures的更高的精确度当RadioButton控件的Checked属性发生更改时。这意味着当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. 
    } 
}