Reputation: 524
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);
}
Upvotes: 0
Views: 11682
Reputation: 99
You can do something like this
//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;
}
This works fine for me
Upvotes: 0
Reputation: 8099
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).
Upvotes: 5