2012-02-10 116 views
2

我有一個勝利的形式,其上有幾個radionbuttons和標籤和一些其他控件,我在運行時生成。當我檢查一個單選按鈕時,不是我想要的,除了我檢查的那個之外,所有的radionbutton都不應該被選中。這適用於每個單選按鈕。簡而言之,我想每次檢查一個radionbutton。防止單選按鈕

private RadioButton GenerateRadioButton(string id) 
     { 
      RadioButton _radioButton = new RadioButton(); 
      _radioButton.Location = new Point(32, 20); 
      _radioButton.Margin = new Padding(4, 4, 4, 4); 
      _radioButton.Size = new Size(130, 36); 
      _radioButton.Name = id; 
      _radioButton.AutoSize = true; 
      _radioButton.Font = new Font("Arial", 16, FontStyle.Bold); 
      _radioButton.CheckedChanged += new System.EventHandler(RadioButton_CheckedChanged); 
      return _radioButton; 
     } 

    private void RadioButton_CheckedChanged(object sender, EventArgs e) 
     { 
      HandleRadioButtinClick(((RadioButton)sender).Name); 
      ((RadioButton)sender).Checked = true; 
     } 

    private void HandleRadioButtinClick(string ctrlId) 
      { 
       FrmSpace objFrmSpace = new FrmSpace(); 
       foreach (Control ctrl in pictureBox1.Controls) 
       { 
        if (ctrl is Panel) 
        { 
         foreach (Control ctl in ctrl.Controls) 
         { 
          if (ctl is RadioButton && ctl.Name != ctrlId) 
           ((RadioButton)ctl).Checked = false; 
         } 
        } 
       } 
      } 

這是上面的代碼。這個代碼的問題是,當我檢查單選按鈕時,如果有其他單選按鈕被選中,並且我試圖取消選中它,checkedchanged事件也會被觸發,導致所有的單選按鈕再次被取消選中。我希望我清楚我想傳達的是什麼。

請提供一些解決方案。

感謝

+0

爲什麼你手動取消選中單選按鈕?你爲什麼不把它們分組來處理這部分。 – 2012-02-10 06:45:00

+0

我很樂意這樣做。但是請問,如何在運行時產生它們的同時對它們進行分組? – 2012-02-10 06:46:23

+0

將它們添加到表單中時,將它們添加到組框中而不是表單。 – 2012-02-10 06:50:00

回答

1

您是否嘗試過使用全部單選按鈕的groupbox?這是您要求的默認功能。

編輯:澄清你的疑問

 // some function 
     GroupBox g = createGBox(); 
     this.Controls.Add(g); 
     g.Controls.Add(radioButton1); 
     g.Controls.Add(radioButton2); 
    } 

    public GroupBox createGBox() 
    { 
     GroupBox gBox = new GroupBox(); 
     gBox.Location = new System.Drawing.Point(72, 105); 
     gBox.Name = "BOX"; 
     gBox.Size = new System.Drawing.Size(200, 100); 
     gBox.Text = "This is a group box"; 
     return gBox; 
    } 
+0

我有一個圖片框,然後在運行時創建面板並將其添加到圖片框。然後我創建標籤和單選按鈕,然後將它們添加到面板中。每個面板都有一組一個單選按鈕和一個標籤。 – 2012-02-10 06:49:58

+0

Groupbox仍然可以工作。只需更換groupbox,而不是包含單選按鈕的面板。檢查鏈接。 Groupbox有一個內置的標籤,您也可以使用。 – Jeremy 2012-02-10 06:55:25

+0

是否有任何groupbox屬性,我需要設置。其實它不工作。與面板相同的結果。 – 2012-02-10 07:02:18

0

把所有radiobuttons到同一GroupBox控制,你可以在運行時創建了。在這種情況下,預期的行爲應該由控制自己處理,而不需要編碼。

希望這會有所幫助。

+0

如果我在設計時使用組框,並在運行時向此組框添加面板(包含單選按鈕和標籤)。它會工作嗎? – 2012-02-10 06:53:03

+0

伊莫,不,你需要GroupBox,就像一個素質父母。你爲什麼要使用面板?直接添加到GroupBox。 – Tigran 2012-02-10 08:01:20