How to add radio buttons dynamically in Windows form?

无人久伴 提交于 2020-08-06 05:43:05

问题


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

回答1:


You could do something like this:

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

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

To get the selected RadioButton use a construct like this:

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

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).



来源:https://stackoverflow.com/questions/44783473/how-to-add-radio-buttons-dynamically-in-windows-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!