问题
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