Reloading Form in C# - c#

I am trying to create a calendar using c# that contains a tab for each month of the year with buttons representing the days located on the tabs (see attached picture). The user can input the desired year into a text box and click a button to submit their request (not on attached picture). Currently, I have the calendar working but I cannot figure out how to redraw the calendar when different years are submitted.
I have tried to follow this example https://stackoverflow.com/a/33104430 but I don’t understand when Form_Load() should be called. I have also tried this.refresh() at various places with no avail.
Any help would be much appreciated.
public Form1()
{
InitializeComponent();
call_on_load();
}
private void call_on_load()
{
pages = tabControl.TabPages;
year = Convert.ToInt16(textBoxYear.Text);
dt = new DateTime(year, 1, 1);
day = -1;
foreach (TabPage page in pages) //declare a page object and cycle through each tab page
{
if (!initialMonth)
{
mth++; //inc month if not first time. Originally set.
}
initialMonth = false;
if (mth > 12) //make a 1 year calendar
break;
//ftime = true;
Console.WriteLine("********************************The date is:" + dt.ToString());
x = ((((int)dt.DayOfWeek) * 75) + 10); //reset x coordinate
y = 20;
for (int rows = 1; rows <= 7; rows++) // # of rows in a month
{ //Some months have 6 rows. Use 7 to ensure the below break statement
if (!ftime)
{
if (dt.Day == 1) //at the top of another month
{
ftime = true;
break;
}
}
ftime = false;
y += 75; //move y coordinate
for (int col = 1; col <= 7; col++) //make 7 columns
{
Button b = new Button();
b.Name = dt.ToString("MMMM") + "_" + Convert.ToString(dt.Day) + "_" + dt.ToString("yyyy"); //store the date in the button name to parse
b.Click += (s, e) => //https://stackoverflow.com/questions/6187944/how-can-i-create-dynamic-button-click-event-on-dynamic-button
{
secondForm = new Form2();
String[] date = b.Name.Split('_');
secondForm.setDate(date[0], Convert.ToInt16(date[1]), Convert.ToInt16(date[2]));
secondForm.Show();
};
b.Size = new Size(50, 50);
b.Left = x;
b.Top = y;
page.Controls.Add(b); //add button to current tab page
// btnInt++;
b.Text = Convert.ToString(dt.Day);
getDate();
Console.WriteLine("The date is:" + dt.ToString());
dt = dt.AddDays(1);
if (dt.Day == 1)
break;
x += 75;
if (x > 460) //if x coordinate is at the end of the line
{
x = 10;
break;
}
}
}
}
}
private void btnSubmitF1_Click(object sender, EventArgs e)
{
year = Convert.ToInt16(textBoxYear.Text);
//this.Refresh(); //does not redraw
call_on_load(); //keeps original layout, does not redraw on button click
//Form_Load(btnSubmitF1,e); //probably not calling this method correctly. Is this method needed?
//this.Refresh(); //does not redraw
}
private void Form_Load(object sender, EventArgs e)
{
call_on_load();
}

I don't think the issue is to do with refreshing the page. I think you're simply not resetting the mth variable and then the if (mth > 12) is always being hit. However, you haven't shown enough code for us to tell for sure.
Also, your code doesn't seem to be very well structured. There's lots of stuff going on that could cause you grief.
To help out I re-wrote the code for you in a way that I think would help.
Try this:
private void call_on_load()
{
var year = Convert.ToInt16(textBoxYear.Text);
var dt = new DateTime(year, 1, 1);
var months =
Enumerable
.Range(0, dt.AddYears(1).Subtract(dt).Days)
.Select(d => dt.AddDays(d))
.GroupBy(x => x.Month);
foreach (var month in months)
{
var tab = tabControl.TabPages[month.Key - 1];
tab.Controls.Clear();
var firstDayOfWeek = (int)month.First().DayOfWeek;
foreach (var date in month)
{
var position = firstDayOfWeek + date.Day - 1;
var button = new Button()
{
Size = new Size(50, 50),
Left = (position % 7) * 75 + 10,
Top = (position / 7) * 75 + 20,
Text = date.ToShortDateString(),
};
button.Click += (s, e) =>
{
var secondForm = new Form2();
secondForm.setDate(date);
secondForm.Show();
};
tab.Controls.Add(button);
}
}
}
I tested this and it seemed to work just fine.

//you just missing a postback maybe, try this.
private void Form_Load(object sender, EventArgs e)
{
if(!IsPostBack){
call_on_load();
}
}
edited
private void btnSubmitF1_Click(object sender, EventArgs e)
{
year = Convert.ToInt16(textBoxYear.Text);
//this.Refresh(); //does not redraw
call_on_load(); //keeps original layout,
//does not redraw on button click
//Form_Load(btnSubmitF1,e); //probably not calling
//this method correctly. Is this method needed?
//this.Refresh(); //does not redraw
this.ParentForm.Refresh();
}

Related

C# - Dynamic buttons with dynamic data-entering

I have a bit of an issue here.
I'm trying to create dynamic clickevents with variable data.
for(int i = 0; i < data.Devices.Length; i++)
{
Button _button = new Button();
_button.Size = new Size(100, 15);
_button.Text = data.Devices[i].Alias;
_button.Name = "textbox" + i.ToString();
_button.Location = new Point(x,y);
x += 110;
if(x > 1850)
{
y += 50;
x = 10;
}
if (data.Devices[i].OnlineState == "Online")
{
_button.BackColor = Color.Green;
}
else
{
_button.BackColor = Color.Red;
}
_button.Click += (Sender, args) =>
{
MessageBox.Show(data.Devices[i].Alias);
};
Controls.Add(_button);
}
The idea here is that I'll create buttons until length of the list is done (The list and position of these objects vary).
What I'm looking for is to make a bunch of buttons, and when you click on the button there should you'll open another screen with some statistics attached to that object.
Since the data will vary A LOT there is no way to hardcode each scenario, but instead I'm looking to do the same thing as you can do in Android, see below.
for (int i = 1; i <= 20; i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setId(i);
final int id_ = btn.getId();
btn.setText("button " + id_);
btn.setBackgroundColor(Color.rgb(70, 80, 90));
linear.addView(btn, params);
btn1 = ((Button) findViewById(id_));
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(), "Button clicked index = " + id_, Toast.LENGTH_SHORT).show();
}
});
Is there any way I can achieve this?
Kind Regards.
I think the problem you are experiencing is regarding closures.
In your example you are adding the event handler with a delegate that's referencing the variable i which changes each loop iteration. So when the event handler is actually executed (when the button is clicked) i is out of scope.
You could do something like this:
private void Form1_Shown(object sender, EventArgs e)
{
var items = new[] { "Item One", "Item Two", "Item Three", "Item Four", "Item Five" };
for (int i = 0; i < items.Length; i++)
{
var btn = new Button
{
Text = $"Button {i + 1}",
Tag = items[i]
};
btn.Click += (object obj, EventArgs args)
=>
{
MessageBox.Show($"Hello. {((Button)obj).Tag}");
};
flowLayoutPanel1.Controls.Add(btn);
}
}
In your case - the button's tag can be set to data.Devices[i] - in other words it doesn't have to be a string it can be an object.
I start off by creating the buttons with the and placing them on the screen.
for (int i = 0; i < data.Devices.Length; i++){
Button _button = new Button();
_button.Size = new System.Drawing.Size(100, 55);
_button.Text = data.Devices[i].Alias;
_button.Name = "dynamicButton";
_button.FlatStyle = FlatStyle.Flat;
_button.Tag = data.Devices[i].Alias + "|" +
data.Devices[i].DeviceId + "|" +
data.Devices[i].LastSeen + "|" +
data.Devices[i].OnlineState + "|" +
data.Devices[i].Description + "|" +
data.Devices[i].RemotecontrolId;
_button.Location = new System.Drawing.Point(x, y);
x += 110;
if (x > 1850)
{
y += 60;
x = 30;
}
_button.Click += new EventHandler(bt_click);
Controls.Add(_button);
}
And then using the onclick event.
protected void bt_click(object sender, EventArgs e)
{
Button btn = sender as Button;
String[] information = btn.Tag.ToString().Split('|');
String present = "Namn: " + information[0]
+ "\nDeviceID: " + information[1]
+ "\nSenast uppe: " + information[2]
+ "\nStatus: " + information[3]
+ "\nEmail: " + information[4]
+ "\nTW-ID: " + information[5];
MessageBox.Show(present);
//DO THE THINGS WITH THE INFORMATION
}
And then to unload everything and eventually updating the status of the device.
for (int i = 0; i < 10; i++)
{
foreach (Control item in Controls.OfType<Control>())
{
if (item.Name == "dynamicButton")
{
Controls.Remove(item);
}
}
}
For some reason I have to loop that thing a couple of times, beacuse it won't delete them all, but instead deleting them in some pattern.
(only takes every other one each time)
I looped it 10 times for good measures.
It does exactly what I want it to do, and new devices gets added automaticly and removed devices dissapears just as fast.

C# delete dynamically added textbox and move all other textboxes down

I have really been struggling with this question for a long time.
I add a textbox and a button on tab press . I put text inside the textboxes:
Now, my question, how do I remove the textbox next to the button I click and move all the textboxes down, so I won't get any open space. If I press on the button next to the 7th textbox, I want it to look like this:
here's my code:
private void Form1_Load(object sender, EventArgs e)
{
//creates a textbox(t0) and a button(b0) on load
TextBox t0 = new TextBox();
t0.Name = "t0";
t0.Location = new Point(16, 12);
t0.Width = 200;
t0.PreviewKeyDown += new PreviewKeyDownEventHandler(PreviewKeyDown);
Button b0 = new Button();
b0.TabStop = false;
b0.Text = "x";
b0.Location = new Point(216, 11);
b0.Size = new System.Drawing.Size(20, 22);
b0.Click += new EventHandler(buttonclicked);
panel1.Controls.Add(t0);
panel1.Controls.Add(b0);
}
private new void PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
//if I press tab in the last textbox it creates a new textbox(t + amount of textboxes) and button(b + amount of textboxes)
if (e.KeyData == Keys.Tab)
{
int counter2 = 0;
foreach (TextBox box in panel1.Controls.OfType<TextBox>())
{
counter2++;
}
counter2 = counter2 - 1;
string Name = "t" + Convert.ToString(counter2);
counter2++;
foreach (TextBox box in panel1.Controls.OfType<TextBox>())
{
if (Name == box.Name && box.Focused)
{
TextBox t0 = new TextBox();
Button b0 = new Button();
t0.Location = new Point(16, 12 + counter - panel1.VerticalScroll.Value);
t0.Width = 200;
t0.Name = "t" + Convert.ToString(counter2);
t0.PreviewKeyDown += new PreviewKeyDownEventHandler(PreviewKeyDown);
b0.TabStop = false;
b0.Text = "x";
b0.Name = "b" + Convert.ToString(counter2);
b0.Location = new Point(216, 11 + counter - panel1.VerticalScroll.Value);
b0.Size = new System.Drawing.Size(20, 22);
b0.Click += new EventHandler(buttonclicked);
panel1.Controls.Add(t0);
panel1.Controls.Add(b0);
counter = counter + 25;
}
}
}
}
private void buttonclicked(object sender, EventArgs e)
{
//Remove the textbox next to it.
}
Any help is appreciated
I suggest you use a TableLayoutPanel. Set the GrowStyle on the TableLayoutPanel to AddRows or AddColumns and then you can add/remove controls to it and it will resize automatically. Set the height of each row to a number a little bigger than the height of the textbox. Set the column widths to a value so the textbox and the button can fit in them. You need 2 columns in it.
You do not need to set the location of the controls to a static location. They will be handled by the TableLayoutPanel for you.
Here is how you can add new controls to it.
yourTableLayoutPanel.Controls.Add(yourTextbox1, 0 /* Column Index */, 0 /* Row index */);

Merge mulitple row Headers in a DatagridView with C#

I have a Project where I need to view data in Datagridview from a Database and it should look like a Gantt Chart.
I would like to let the Datagridview look like this:
Datagridview example
I already tried a lot of code from the internet, but nothing worked properly
For example this one:
https://social.msdn.microsoft.com/Forums/windows/en-US/87004d70-482a-4b86-ba18-371670254b6a/how-to-merge-headers-in-a-datagridview?forum=winformsdatacontrols
Also I don't know how to get the day values into the cells/row header
This is how I get the days from a month
int year = DateTime.Now.Year;
int Jan = 1;
int daysInJan = System.DateTime.DaysInMonth(year, Jan);
The linked solution works fine for the example it provides. That said:
I wasn't able to get more than 2 columns under a title
From our discussion in comments, I thought it sufficient that you simply add additional column widths to stretch a "main" title over more than 2 columns. This was fine, until I tested with enough columns to permit horizontal scrolling. It was then that I noticed that the "main" title of a month was only displayed when the 1st day column of that month was visible.
The following code will address these issues:
Stretching over 2+ columns.
Displaying the "main" title through resizes and regardless of 1st column visibility.
how to get the day values into the cells/row header
General cleanup of IDisposable objects and refactoring.
In the Form, to set up the grid do the following:
private int[] daysInMonths;
private void Form1_Load(object sender, EventArgs e)
{
int year = DateTime.Now.Year;
daysInMonths = new int[12];
// Add a column for each day of the year; where
// column name = the date (creates all unique column names)
// column header text = the numeric day of the month
for (int month = 1; month <= 12; month++)
{
daysInMonths[month - 1] = DateTime.DaysInMonth(year, month);
// for days 1-31, 1-29, etc.
for (int day = 1; day <= daysInMonths[month - 1]; day++)
{
DateTime date = new DateTime(year, month, day);
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn()
{
Name = date.ToString(),
HeaderText = day.ToString(),
Width = 20
};
this.dataGridView1.Columns.Add(col);
}
}
// add some default rows
for (int r = 0; r < 4; r++)
{
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(this.dataGridView1);
row.HeaderCell.Value = $"Project {r + 1}";
this.dataGridView1.Rows.Add(row);
}
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
this.dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
this.dataGridView1.ColumnHeadersHeight = this.dataGridView1.ColumnHeadersHeight * 2;
this.dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter;
this.dataGridView1.Paint += DataGridView1_Paint;
this.dataGridView1.Scroll += DataGridView1_Scroll;
this.dataGridView1.ColumnWidthChanged += DataGridView1_ColumnWidthChanged;
this.dataGridView1.Resize += DataGridView1_Resize;
}
Then add your event handlers:
private void InvalidateHeader()
{
Rectangle rtHeader = this.dataGridView1.DisplayRectangle;
rtHeader.Height = this.dataGridView1.ColumnHeadersHeight / 2;
this.dataGridView1.Invalidate(rtHeader);
}
private void DataGridView1_Resize(object sender, EventArgs e)
{
this.InvalidateHeader();
}
private void DataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
{
this.InvalidateHeader();
}
private void DataGridView1_Scroll(object sender, ScrollEventArgs e)
{
this.InvalidateHeader();
}
private void DataGridView1_Paint(object sender, PaintEventArgs e)
{
int col = 0;
// For each month, create the display rectangle for the main title and draw it.
foreach (int daysInMonth in daysInMonths)
{
Rectangle r1 = this.dataGridView1.GetCellDisplayRectangle(col, -1, true);
// Start the rectangle from the first visible day of the month,
// and add the width of the column for each following day.
for (int day = 0; day < daysInMonth; day++)
{
Rectangle r2 = this.dataGridView1.GetCellDisplayRectangle(col + day, -1, true);
if (r1.Width == 0) // Cell is not displayed.
{
r1 = r2;
}
else
{
r1.Width += r2.Width;
}
}
r1.X += 1;
r1.Y += 1;
r1.Height = r1.Height / 2 - 2;
r1.Width -= 2;
using (Brush back = new SolidBrush(this.dataGridView1.ColumnHeadersDefaultCellStyle.BackColor))
using (Brush fore = new SolidBrush(this.dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor))
using (Pen p = new Pen(this.dataGridView1.GridColor))
using (StringFormat format = new StringFormat())
{
string month = DateTime.Parse(this.dataGridView1.Columns[col].Name).ToString("MMMM");
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
e.Graphics.FillRectangle(back, r1);
e.Graphics.DrawRectangle(p, r1);
e.Graphics.DrawString(month, this.dataGridView1.ColumnHeadersDefaultCellStyle.Font, fore, r1, format);
}
col += daysInMonth; // Move to the first column of the next month.
}
}

Label text not updating

public void ItemGot()
{
number = number + 1; //Increment by 1
quantity.Text = ("x" + number); //Overwrite Text
quantity.Refresh(); //Updates the text
}
Hello, I have this code above. When this method runs, the text of a label I set up earlier should change the text to the one i set below. However, its not doing it. Furthermore, by setting breakpoints in Visual Studio, I have determined that:
The method is being called,
Number is being incremented properly.
There should be NO reason why this not working, because the program is recognizing that number is increasing by one. My friend said a similar question here. Still no help, and now that code is outdated. Please help!
EDIT: how I added the quantity label
First, I initialized it in the constructor: public Label quantity;
Then I did this: quantity = new Label();
Lastly, in another method, I gave the quantity the following properties:
quantity.Size = new Size(24, 24);
quantity.Text = ("x" + number);
quantity.Left = 48;
Controls.Add(quantity);
number is also in the constructor and is set to 0.
EDIT 2 : I'll Post my whole method
public InventoryScreen()
{
btnItems = new Button();
quantity = new Label();
//call the methods for spawning the buttons
ButtonGenItems(cNumber, btnItems, quantity);
InitializeComponent();
}
public void InventoryScreen_Load(object sender, EventArgs e)
{
}
#region ButtonGenItems Method
public void ButtonGenItems(int cNumber, Button btnItems,Label quantity)
{
int xPos = 126;
int yPos = 25;
for (int n = 0; n < 1; n++)
{
btnItems.Tag = n;
btnItems.Size = new Size(48, 52); //Button size X and Y
btnItems.BackColor = Color.CornflowerBlue;
quantity.Size = new Size(24, 24);
quantity.Text = ("x" + number);
if (yPos > 60) // Five Buttons in one column
{
yPos = 25; //spawn position Y
xPos = xPos + btnItems.Width + 10; //spacing X
}
btnItems.Left = xPos; //Start Button spawn at the Left side
btnItems.Top = yPos; //Start spawn at the top side
quantity.Left = 48;
quantity.Top = 60;
yPos = yPos + btnItems.Height + 10;
btnItems.Text = "Use";
Controls.Add(btnItems); //place Buttons
Controls.Add(quantity);
// the Event of click Button
//btnItems.Click += new System.EventHandler(ItemUse); //to be implimented
}
}
#endregion
public void ItemGot()
{
//*Interestingly, the program recognizes that 'number' is increasing by 1, but label won't update the text
//Furthermore, pressing the actual button will trigger the text update, but simulating a buttonclick WONT DO ANYTHING
Console.WriteLine("Text should now increment by 1"); //Debugging to test method
number = number + 1; //Increment by 1
quantity.Text = ("x" + number); //Overwrite Text
}
}
2.5 This is how the method is being called. This method is located in another class
public void Update(Vector2 pos)
{
this.position = pos; //get char position
Inv = new InventoryScreen(); //create instance of object
charRange = new Rectangle((int)position.X, (int)position.Y, 64, 57); //create rectangle
//Intersection Code, If the character intersects with the item while the item is showing, run below
if (alive && charRange.Intersects(itemRect))
{
alive = false; //stop showing the item
Inv.ItemGot(); //Call the ItemGot class, which adds the item to the inventory screen
}
}
As I understand you have already open/showed form(instance of class InventoryScreen) with your label when you calling Update method, But...
Inside of method Update you creating a new instance of InventoryScreen, and calling function ItemGot with this new instance of form.
I think you need to pass reference of your current instance of InventoryScreen in method Update, then use that reference for calling ItemGot method
public void Update(Vector2 pos, InventoryScreen invscreen)
{
this.position = pos;
charRange = new Rectangle((int)position.X, (int)position.Y, 64, 57);
if (alive && charRange.Intersects(itemRect))
{
alive = false;
invscreen.ItemGot();
}
}

storing multiple controls and update radio button values?

What am doing here is; making a UI to update values visually, will add more support for other types too. Possibly all types.
updateIcons this function is called everytime the controller is loaded, and has new values,names everytime.
countControls to keep track of controllers, so if can update values on clicks.
myP is the object that holds the values taken at runtime, user shuffles values by pressing tab from another screen
created radiobuttons groupboxes to allow radiobutton group to be managed.
properties all belong to one object. each property has few possible values like in my example, the enums.
now am kinda lost, not sure how to best do this, as now my rb_CheckedChanged is returning some kind of mess.
How do i do this the right way ? all together, i feel its somewhat the right approach At least.
I thought of making a dictionary of ? to use it at the checked event. not exactly sure how
private void updateIcons(List<Props> prop) {
countControls++;
locationY = 10;
int gbHeight;
foreach (var p in prop) {
radioButtonY = 10;
IType pType = p.Type;
if (pType is Enum) {
var myP = new MyProp(p, this);
GroupBox gb = new GroupBox();
gb.Location = new Point(nextLocationX,locationY);
nextLocationX += rbWidth+10;
gb.Name = "groupBox" + countControls;
gb.Text = "smthn";
var TypesArray = set here;
gbHeight = TypesArray.Length;
foreach (var type in TypesArray) {
getimagesPath(TypesArray);
RadioButton rb = new RadioButton();
rb.Appearance = Appearance.Button;
rb.Width = rbWidth;
rb.Height = rbHeight;
rb.Name = type.Name + countControls;
rb.Text = type.Name;
string path = imagePaths[type.Name];
Bitmap rbImage = new Bitmap(path);
rb.BackgroundImage = rbImage;
countControls++;
rb.Location = new Point(radioButtonX, radioButtonY);
if (myP.Value != null && type.Name.SafeEquals(myP.Value.ToString())) {
rb.Checked = true;
}
radioButtonY += rbHeight;
gb.Controls.Add(rb);
rb.CheckedChanged += rb_CheckedChanged;
}
gb.Height = rbHeight * gbHeight + 20;
gb.Width = rbWidth + 10;
Controls.Add(gb);
}
}
}
void rb_CheckedChanged(object sender, EventArgs e) {
RadioButton rb = (RadioButton)sender;
Control control = (Control)sender;
if (rb.Checked) {
MessageBox.Show("You have just checked: " + rb.Text);
MessageBox.Show("You have just called Controller: " + control.Name);
var t = PropSeq;
}
else {
MessageBox.Show("you have just unchecked: " + rb.Text);
MessageBox.Show("You have just called Controller: " + control.Name);
}
}
I think your code might be a little messed up and not the easiest to read. It looks plain invalid with not all closing braces present? Try the code below which will create two group boxes, each with five radio buttons. This should help you achieve what you are trying to do (full listing for a basic Form):
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CreateButton();
}
private void CreateButton()
{
// Add two group boxes
for (int groupCount = 1; groupCount < 3; groupCount++)
{
var groupBox = new GroupBox();
groupBox.Location = new Point(220 * (groupCount - 1), 10);
groupBox.Name = string.Format("groupBox{0}", groupCount);
groupBox.Text = string.Format("Group Box {0}", groupCount);
// Add some radio buttons to each
for (int buttonCount = 1; buttonCount < 6; buttonCount++)
{
var radioButton = new RadioButton();
radioButton.Width = 150;
radioButton.Location = new Point(10, 30 * buttonCount);
radioButton.Appearance = Appearance.Button;
radioButton.Name = string.Format("radioButton{0}", buttonCount);
radioButton.Text = string.Format("Dynamic Radio Button {0} - {1}", groupCount, buttonCount);
radioButton.CheckedChanged += radioButton_CheckedChanged;
// Add radio button to the group box
groupBox.Controls.Add(radioButton);
groupBox.Height += 20;
}
// Add group box to form
Controls.Add(groupBox);
}
}
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
// Get button and only show the selected (not now de-selected item)
var radioButton = (RadioButton)sender;
if (radioButton.Checked)
{
MessageBox.Show("You have just checked: " + radioButton.Text);
}
}
}
}

Categories