c# - 防止单选按钮点击

标签 c# winforms windows-applications

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

请提供一些解决方案。

谢谢

最佳答案

您是否尝试过使用 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;
    }

关于c# - 防止单选按钮点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9223772/

相关文章:

c# - 线程与后台 worker

c# - 如何禁用 dataGridView 中不可点击的按钮(c# windows 应用程序)

c# - 在 C# 中转换数组

c# - 如何创建动态 Entity Framework 过滤表达式,如 Expression<Func<T, bool>>

c# - 如何本地化 UserControl

c# - 表单 DataGridView 缺少 OnRowDataBound?

c# - URL 在浏览器中有效,但无法从 Web 客户端或 Web 请求获取响应

c# - 如何在控制台应用程序中捕获未处理的异常

c# - 在表格的列标题处插入间距

c# - 有没有办法从 WinForms 应用程序打开 Windows 日期和时间设置对话框?