How to add radio buttons dynamically in Windows form? - c#

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

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

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

Related

How to put GroupBoxes next to each other

I have dynamically genereted group box with label inside
int dlugoscChuja = 0;
string przedmiot = "";//random strings
for (int i = 0; i < 5; i++)
{
GroupBox g = new GroupBox();
g.AutoSize = true;
g.Visible = true;
g.AutoSizeMode = AutoSizeMode.GrowAndShrink;
var lb = new Label();
lb.AutoSize = true;
lb.Location = new Point(6, 16);
lb.Text = przedmiot;
g.Controls.Add(lb);
dlugoscChuja += lb.Width;
if (i != 0)
{
g.Location = new Point((i*(g.Width+g.Padding.Size.Width)-100), 12);
}
else
{
g.Location = new Point(0, 12);
}
this.Controls.Add(g);
}
how i can put those group boxes next to each other?
my kod (i*(g.Width+g.Padding.Size.Width)-100) of course does not work, is there eany proffesional way to place them? If my labels text is longer of course my group box have more width
You can use Flowlayoutpanel inside your groupbox
We can set the direction of items in Flowlayoutpanel to
TopDown
LeftToRight
RightToLeft
BottomUp
Instead of adding labels to groupBox add it to FlowLayoutpanel
//groupbox must outsideloops
GroupBox g = new GroupBox();
g.AutoSize = true;
g.Visible = true;
g.AutoSizeMode = AutoSizeMode.GrowAndShrink;
var flowPanel;
for (int i = 0; i < 5; i++)
{
flowPanel = new FlowLayoutPanel();
flowPanel.Size = g.Size; // set size of flowpanel to groupbox
flowPanel.Dock = DockStyle.Fill; // Fill parent size
flowPanel.FlowDirection = FlowDirection.TopDown;//Use above directions
var lb = new Label();
lb.AutoSize = true;
lb.Location = new Point(6, 16);
lb.Text = przedmiot;
flowPanel.Controls.Add(lb);//lb your labe
}
g.Controls.Add(flowPanel);//finally add flowpanel to groupbox
this.Controls.Add(g);

How to hide dynamically created controls in scrollable panel

I have a problem, because in my code I am dynamically creating new buttons, and after that, the window looks in that way:
This is code that I used for that:
private void DrawButtons()
{
for (int i = 0; i < 90; i++)
{
Button button = new Button();
button.Location = new Point(15 + 40 * i, 10);
button.Size = new Size(35, 30);
button.Parent = panel4;
button.Tag = i;
Controls.Add(button);
button.BringToFront();
}
}
I want to have scrollable panel, like there, where I created buttons manually:
What I must do to have this effect with programically created elements?
You can use the AutoScroll property. For Panel:
panel4.AutoScroll = true;
But you should also set this property:
button.Anchor = AnchorStyles.Left;
And also add the button to your Panel:
panel4.Controls.Add(button);
So this should be what you want:
private void DrawButtons()
{
for (int i = 0; i < 90; i++)
{
...
button.Anchor = AnchorStyles.Left;
...
panel4.Controls.Add(button);//Add this also
...
}
panel4.AutoScroll = true;
}
The result:

C# How to put RadioButton inside Panel

I have searched everywhere, but the procedure are so painful. How to put multiple RadioButton into a panel programatically without using toolbox. I'm using WinForms. After several suggestion/s, I still can't add the radiobuttons inside the panel.
public partial class Form1 : Form
{
RadioButton[] RadioButton_WallFirstStorey_Yes = new RadioButton[100];
RadioButton[] RadioButton_WallFirstStorey_No = new RadioButton[100];
Panel[] Panel_WallFirstStorey = new Panel[100];
int CheckBoxWidth = 100;
public Form1()
{
InitializeComponent();
//code
//procedure
}
private void InitializeRadioButton_Wall(RadioButton RadioButtonX)
{
RadioButtonX.AutoSize = true;
RadioButtonX.Font = SystemFonts.DefaultFont;
RadioButtonX.BackColor = Color.Transparent;
Controls.Add(RadioButtonX);
}
private void InitializePanel_Wall(Panel PanelX)
{
PanelX.BackColor = Color.PaleTurquoise;
PanelX.BorderStyle = BorderStyle.Fixed3D;
PanelX.BringToFront();
Controls.Add(PanelX);
}
private void MyProcedure()
{
int i;
for (i = 1; i <= 100; i++)
{
Panel_WallFirstStorey[i] = new Panel();
InitializePanel_Wall(Panel_WallFirstStorey[i]);
Panel_WallFirstStorey[i].Location = new Point(Label_SeparatorLineVertical[ColumnMinimum + i].Location.X, Label_SeparatorLineHorizontal[RowMinimum + i].Location.Y);
Panel_WallFirstStorey[i].Width = (Label_SeparatorLineVertical[ColumnMaximum].Location.X - Label_SeparatorLineVertical[ColumnMinimum].Location.X) / (ColumnMaximum - ColumnMinimum);
Panel_WallFirstStorey[i].Height = CheckBoxWidth;
Panel_WallFirstStorey[i].SendToBack();
}
for (i = 1; i <= 100; i++)
{
RadioButton_WallFirstStorey_Yes[i] = new RadioButton();
RadioButton_WallFirstStorey_No[i] = new RadioButton();
Panel_WallFirstStorey[i].Controls.Add(RadioButton_WallFirstStorey_Yes[i]);//I add this stuff
Panel_WallFirstStorey[i].Controls.Add(RadioButton_WallFirstStorey_No[i]);//I add this stuff
InitializeRadioButton_Wall(RadioButton_WallFirstStorey_Yes[i]);
InitializeRadioButton_Wall(RadioButton_WallFirstStorey_No[i]);
RadioButton_WallFirstStorey_Yes[i].Text = "Yes";
RadioButton_WallFirstStorey_No[i].Text = "No";
RadioButton_WallFirstStorey_Yes[i].Location = new Point(Panel_WallFirstStorey[i].Width / 3, 0);
RadioButton_WallFirstStorey_No[i].Location = new Point(Panel_WallFirstStorey[i].Width * 2 / 3, 0);
RadioButton_WallFirstStorey_Yes[i].Font = SystemFonts.DefaultFont;
RadioButton_WallFirstStorey_No[i].Font = SystemFonts.DefaultFont;
RadioButton_WallFirstStorey_Yes[i].BringToFront();
RadioButton_WallFirstStorey_No[i].BringToFront();
}
}
}
Wow, your code is wrong in so many ways.... It creates controls over and over whenever a panel is painted, but it never really adds them anywere.
To add a radio button b to a panel p, it would be enough to do this:
RadioButton b = new RadioButton();
// Set properties for button here (text, location, handlers, etc.)
p.Controls.Add(b);
I'd try the following procedure instead of yours:
private void MyProcedure()
{
for (i = 1; i <= 100; i++)
{
RadioButton_WallFirstStorey_Yes[i] = new RadioButton();
RadioButton_WallFirstStorey_No[i] = new RadioButton();
InitializeRadioButton_Wall(RadioButton_WallFirstStorey_Yes[i]);
InitializeRadioButton_Wall(RadioButton_WallFirstStorey_No[i]);
RadioButton_WallFirstStorey_Yes[i].Text = "Yes";
RadioButton_WallFirstStorey_No[i].Text = "No";
RadioButton_WallFirstStorey_Yes[i].Location = new Point(Panel_WallFirstStorey[i].Location.X + Panel_WallFirstStorey[i].Width / 3, Panel_WallFirstStorey[i].Location.Y);
RadioButton_WallFirstStorey_No[i].Location = new Point(Panel_WallFirstStorey[i].Location.X + Panel_WallFirstStorey[i].Width * 2 / 3, Panel_WallFirstStorey[i].Location.Y);
Panel_WallFirstStorey[i].Controls.Add(RadioButton_WallFirstStorey_Yes[i]);
Panel_WallFirstStorey[i].Controls.Add(RadioButton_WallFirstStorey_No[i]);
}
}
The following code indicates you're still doing it wrong, adding the radio buttons to the form itself, but positioning them as if you had added them to the panel:
RadioButton_WallFirstStorey_Yes[i].Location = new Point(Panel_WallFirstStorey[i].Location.X + Panel_WallFirstStorey[i].Width / 3, Panel_WallFirstStorey[i].Location.Y);
If you added the button to the panel, it would most probably be invisible because it is outside the panel. If you added the button to the panel, you'd have to use coordinates relative to the panel's client area.
RadioButton_WallFirstStorey_Yes[i].Location = new Point(Panel_WallFirstStorey[i].Width / 3, 0);
RadioButton_WallFirstStorey_No[i].Location = new Point(Panel_WallFirstStorey[i].Width * 2 / 3, 0);
Your update code shows clearly where your error is:
private void InitializeRadioButton_Wall(RadioButton RadioButtonX)
{
RadioButtonX.AutoSize = true;
RadioButtonX.Font = SystemFonts.DefaultFont;
RadioButtonX.BackColor = Color.Transparent;
// REMOVE THIS LINE!!
Controls.Add(RadioButtonX);
}
The last line adds the radio button to the form. As we've been telling you all the time. Remove the line I marked above. Then, the radio buttons will be added to the panels only. After that it is a question of getting the positions right.
You can for example create a panel (or a GroupBox) and in a loop add the RadioButtons.
It should work like with any other control in Winforms.
// Adds 10 Radiobuttons with the name "Radio <number>"
public Form1()
{
InitializeComponent();
for (int n = 0; n < 10; n++)
{
// First instantiate a new RadioButton.
RadioButton button = new RadioButton();
// Now the name of the button.
button.Text = "Radio" + n;
// Dock the button to the top of the GroupBox (to put them in order)
button.Dock = DockStyle.Top;
// Add the button to the GroupBox.
this.groupBoxRadio.Controls.Add(button);
}
}
Your question is not very clear, and no code for context, but you should be able to create an instance of a new radiobutton and add it to the controls of the panel.
It may also be best to use RadioButtonList like Harvey has mentioned, but to try to answer your question:
var someRadioBtn = new RadioButton();
// set properties...
pnlMyPanel.Controls.Add(someRadioBtn);

How to set different events for dynamically created element

Im trying to create event with different index for dynamically created GroupBox. With my actual code event for every groupbox is that same. How can i make event with different index for every groupbox? My Code:
public void LoadGry()
{
// GroupBox groupbox = new GroupBox();
Label nazwagry = new Label();
for(int i = 0; i < myCollection.Count; i++)
{
GroupBox groupbox = new GroupBox();
groupbox.Text = myCollection[i];
groupbox.Size = new Size(290, 131);
groupbox.Location = new Point(6, 150 * (myCollection.Count - i - 1));
groupbox.ForeColor = Color.White;
Label label1 = new Label();
label1.Text = groupbox.Text;
label1.AutoSize = true;
label1.Location = new Point(groupbox.Location.X + 80, groupbox.Location.Y + 20);
groupbox.Controls.Add(label1);
Gry.Controls.Add(label1);
PictureBox picturebox = new PictureBox();
picturebox.Location = new Point(groupbox.Location.X + 5, groupbox.Location.Y + 20);
picturebox.Size = new Size(75, 75);
picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
picturebox.LoadAsync(myCollection3[i]);
groupbox.Click += new EventHandler(delegate {groupboxclick(groupbox, picturebox, i);});
Label label2 = new Label();
label2.Text = "Status: " + "Aktualny";
label2.ForeColor = Color.Green;
label2.AutoSize = true;
label2.Location = new Point(label1.Location.X, label1.Location.Y + 20);
Gry.Controls.Add(label2);
Label zapiszopis = new Label();
zapiszopis.Text = myCollection4[i];
zapiszopis.Visible = false;
Gry.Controls.Add((Control)groupbox);
//MessageBox.Show("pokaz mi wysokosc");
}
}
private void groupboxclick(GroupBox groupbox, PictureBox picturebox, int itest)
{
groupbox.ForeColor = Color.Aqua;
this.pictureBox1.BackgroundImage = picturebox.BackgroundImage;
opishacka.Text = myCollection4[itest];
}
The problem is that the event setup is using the variable K value. For use the number instead you probably needs to create an expression manually to use the current value in each case.
BUT
You can easily do what you want using the following properties to attach values to controls.
1-) Tag in WinForms & WPF:
// Setup
pictureBox.Tag = i;
// Event
int i = (int) pictureBox.Tag;
2-) ViewState in WebForms
// Setup
ViewState[pictureBox.UniqueID] = i;
// Event
int i = (int) ViewState[pictureBox.UniqueID];
You can use many other techniques. I only post one for each popular framework. I guest that you are in a WinFors project.
Hope this help!

C# Add Controls To Panel In a Loop

I wish to add a button for every line in a file to a panel.
My code so far is:
StreamReader menu = new StreamReader("menu.prefs");
int repetition = 0;
while(!menu.EndOfStream)
{
Button dynamicbutton = new Button();
dynamicbutton.Click += new System.EventHandler(menuItem_Click);
dynamicbutton.Text = menu.ReadLine();
dynamicbutton.Visible = true;
dynamicbutton.Location = new Point(4+repetition*307, 4);
dynamicbutton.Height = 44;
dynamicbutton.Width = 203;
dynamicbutton.BackColor = Color.FromArgb(40,40,40);
dynamicbutton.ForeColor = Color.White;
dynamicbutton.Font = new Font("Lucida Console", 16);
dynamicbutton.Show();
menuPanel.Controls.Add(dynamicbutton);
repetition++;
MessageBox.Show(dynamicbutton.Location.ToString());
}
menu.Close();
The problem is that only the first control gets created.
The code looks fine but there could be a following situations.
1.You might have only one entry in the file, so you are experiencing only One Button added to the panel.
2.Your panel width is smaller than the sum of all the dynamic buttons width.
I suspect no 2 is the main reason that is causing problem.
So, I recommend that you use FlowLayoutPanel. To add a dynamic content as it automatically layout all the child controls.
Each time it is generating the same name for dynamic controls. That's the reason why it is showing only the last one. It simply overwrites the previous control each time.
int x = 4;
int y = 4;
foreach(PhysicianData pd in listPhysicians)
{
x = 4;
y = panPhysicians.Controls.Count * 30;
RadioButton rb = new RadioButton();
rb.CheckedChanged += new System.EventHandler(rbPhysician_CheckedChanged);
rb.Text = pd.name;
rb.Visible = true;
rb.Location = new Point(x, y);
rb.Height = 40;
rb.Width = 200;
rb.BackColor = SystemColors.Control;
rb.ForeColor = Color.Black;
rb.Font = new Font("Microsoft Sans Serif", 10);
rb.Show();
rb.Name = "rb" + panPhysicians.Controls.Count;
panPhysicians.Controls.Add(rb);
}
Try this code
StreamReader menu = new StreamReader("menu.prefs");
var str = menu.ReadToEnd();
var items = str.Split(new string[] {"\r\n" } , StringSplitOptions.RemoveEmptyEntries);
foreach (var item in items)
{
Button dynamicbutton = new Button();
dynamicbutton.Click += new System.EventHandler(menuItem_Click);
dynamicbutton.Text = item;
dynamicbutton.Visible = true;
dynamicbutton.Location = new Point(4+repetition*307, 4);
dynamicbutton.Height = 44;
dynamicbutton.Width = 203;
dynamicbutton.BackColor = Color.FromArgb(40,40,40);
dynamicbutton.ForeColor = Color.White;
dynamicbutton.Font = new Font("Lucida Console", 16);
dynamicbutton.Show();
menuPanel.Controls.Add(dynamicbutton);
repetition++;
}
The problem with Panel and similar controls other than the FlowLayoutPanel is when you create a control and a second one, the second is created at the same position if you are not changing it's location dynamically or setting it according to the other already added controls. Your control is there, it's in the back of the first control.
A flowLayoutPanel is better as it will add the controls next to each other as you add them while compromising more finer control at their positioning.
I also have similar problems with panels. For what you are doing it could be useful to just add strings to a listbox rather than using labels and a panel. That should be simpler.

Categories