2013-02-17 85 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. 
    } 
}