【问题标题】:How to add radio buttons dynamically in Windows form?如何在 Windows 窗体中动态添加单选按钮?
【发布时间】:2017-11-30 16:42:00
【问题描述】:

我需要在我的窗口窗体和水平模式下动态添加单选按钮。

for (int i = 0; i <= r.Count; i++)
{
RadioButton rdo = new RadioButton();
rdo.Name = "id";
rdo.Text = "Name";
rdo.ForeColor = Color.Red;
rdo.Location = new Point(5, 30 );
this.Controls.Add(rdo);
}

【问题讨论】:

  • 太棒了/你试过什么
  • this 之类的东西能回答你的问题吗?
  • @MarkC。我使用了相同的链接,但它垂直显示单选按钮

标签: c# winforms radio-button


【解决方案1】:

你可以这样做

//This is my dynamic data list
List<ItemType> itemTypeData = new List<ItemType>()

RadioButton[] itemTypes = new RadioButton[ItemType.Count];
int locationX = 0;
for (int i = 0; i < ItemType.Count; i++)
{
     var type = ItemType[i];
     itemTypes[i] = new RadioButton
     {
         Name = type.Code,
         Text = type.Code,
         AutoSize = true,
         Font = new System.Drawing.Font("Calibri", 11F, FontStyle.Regular),
         Location = new Point(156 + locationX, 88),
     };
                
     this.Controls.Add(itemTypes[i]);
     locationX += 80;
}

这对我来说很好用

【讨论】:

    【解决方案2】:

    你可以这样做:

    FlowLayoutPanel pnl = new FlowLayoutPanel();
    pnl.Dock = DockStyle.Fill;
    
    for (int i = 0; i < 4; i++)
    {
        pnl.Controls.Add(new RadioButton() { Text = "RadioButton" + i });
    }
    
    this.Controls.Add(pnl);
    

    您还可以在设计器中添加FlowLayoutPanel,并将该部分留在代码中。

    要获得选定的RadioButton,请使用如下构造:

    RadioButton rbSelected = pnl.Controls
                             .OfType<RadioButton>()
                             .FirstOrDefault(r => r.Checked);
    

    要使用它,FlowLayoutPanel 需要在调用方法中知道。所以要么将它添加到设计器中的Form(这就是我更喜欢的),要么将它创建为表单的实例成员并在运行时添加它(这没有任何好处)。

    【讨论】:

    • 没关系。如果这是您的问题的解决方案,请标记为正确答案
    • 您能否告诉我如何在单击保存按钮时获取选定的单选按钮 ID? @Romano Zumbe
    • 你能建议一下吗
    • 为了清楚起见,Romano 的回答现在显示了如何获取选定的单选按钮。
    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    相关资源
    最近更新 更多