2

我有一个 win 表单,上面有几个单选按钮和标签以及我在运行时生成的一些其他控件。当我检查一个单选按钮时,这不是我想要的,除了我检查的那个之外,所有的单选按钮都应该被​​取消选中。这适用于每个单选按钮。简而言之,我希望一次检查一个单选按钮。

 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 事件也会被触发,这会导致所有单选按钮再次被取消选中。我希望我清楚我想要传达的内容。

请提供一些解决方案。

谢谢

4

2 回答 2

1

您是否尝试过为所有单选按钮使用组框?这是您要求的默认功能。

编辑:澄清你的问题

        // 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;
    }
于 2012-02-10T06:47:40.617 回答
0

将所有内容radiobuttons放入同一个GroupBox控件中,您也可以在运行时创建该控件。在这种情况下,预期的行为应该由控件本身来处理,而不需要编码。

希望这可以帮助。

于 2012-02-10T06:48:27.350 回答