如何在 Windows 窗体中动态添加单选按钮? [英] How to add radio buttons dynamically in Windows form?

查看:63
本文介绍了如何在 Windows 窗体中动态添加单选按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to add radio buttons dynamically in my windows form and in horizontal mode.

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);
}

推荐答案

你可以这样做:

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 并在代码中保留该部分.

You could also add the FlowLayoutPanel in the designer and leave that part out in the code.

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

To get the selected RadioButton use a construct like this:

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

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

To use this the FlowLayoutPanel needs to be known in the calling method. So either add it to the Form in the designer (Thats what I would prefer) or create it as an instance member of the form and add it at runtime (this has no benefit).

这篇关于如何在 Windows 窗体中动态添加单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆