防止单击按钮

时间:2012-02-10 06:40:55

标签: c# winforms windows-applications

我有一个win表单,其中有几个radionbuttons和标签以及我在运行时生成的一些其他控件。当我检查一个无线电按钮时,不是我想要的,除了我检查的那个之外,所有的辐射按钮都应该是不受控制的。这适用于每个单选按钮。简而言之,我希望一次检查一个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事件也会被触发,这会导致所有的radiobutton再次被取消选中。我希望我很清楚我想传达的内容。

请提供一些解决方案。

由于

2 个答案:

答案 0 :(得分: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;
    }

答案 1 :(得分:0)

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

希望这有帮助。

相关问题