将许多单选按钮添加到 groupbox C#

Posted

技术标签:

【中文标题】将许多单选按钮添加到 groupbox C#【英文标题】:Add many radio buttons to groupbox C# 【发布时间】:2021-07-16 19:30:05 【问题描述】:

如果 x 我想显示特定数量的单选按钮,我在文本框中有值,如果 y 显示其他特定数量的单选按钮,那么如何添加特定数量的单选按钮并通过代码控制其位置和大小,谢谢

【问题讨论】:

WinForms,WPF,还有什么? 对于 WinForms C# 你有没有做过任何研究或尝试自己写任何东西? 【参考方案1】:

您可以尝试实现旧的 for 循环。如果您想创建垂直堆叠的单选按钮:

  //TODO: provide the desired value here
  int numberOfRadioButtons = 7;

  //TODO: Put desired values here
  int left = 15;
  int top = 25;
  int height = 50;

  for (int i = 0; i < numberOfRadioButtons; ++i) 
    RadioButton button = new RadioButton() 
      Parent = myGroupBox,
      Location = new Point(left, top + height * i),
      Text = $"RadioButton # i",

      // If you insist on setting size manually, uncomment the lines below
      //AutoSize = false,
      //Size = new Size(200, height),
    ;

    // button is created; you can use it, say, to assign event handler:
    //button.Click += MyRadioButtonClick;
  

编辑:您可以使用Linq检查RadioButton

  using System.Linq;

  ...

  // Either checked rudio button or null if none of radio button is checked
  RadioButton chosen = myGroupBox
    .Controls
    .OfType<RadioButton>()
    .FirstOrDefault(button => button.Checked); 

【讨论】:

非常感谢,但我可以根据选择的内容获取文本

以上是关于将许多单选按钮添加到 groupbox C#的主要内容,如果未能解决你的问题,请参考以下文章

C# 中带有单选按钮的 groupBox 的事件处理程序

如何用单选按钮替换 Groupbox Text 属性?

Axure:切换单选按扭,控制界面显示不同内容

如何通过软件取消链接没有 GroupBox 的所有单选按钮

如何将单选按钮添加到菜单项?

在 TableView 的自定义单元格中添加单选按钮并且无法访问外部