dynamically added checkboxes in windows forms - c#

I have added check boxes dynamically to a panel. now how can i get a alert message with "you have checked 1 or 2 or 3....". when check boxes get selected??
CheckBox[] premiumticket = new CheckBox[50];
private void Form1_Load(object sender, EventArgs e)
{
var panel1 = new Panel()
{
Size = new Size(600, 70),
Location = new Point(20, 130),
BorderStyle = BorderStyle.FixedSingle
};
for (int i = 0; i < 20; i++)
{
premiumticket[i]=new CheckBox();
premiumticket[i].Text=(i+1).ToString();
premiumticket[i].Name=(i+1).ToString();
premiumticket[i].Location=new Point(x,y);
panel1.Controls.Add(premiumticket[i]);
x = x - 55;
if (x < 55)
{
y = y + 20;
x = 550;
}
}
x = 550; y = 10;
Controls.Add(panel1);
}

Add an event-handler to each CheckBox:
public void Checkbox_CheckedChanged(Object sender, EventArgs e) {
CheckBox cb = (CheckBox)sender;
MessageBox.Show( cb.Name + " was clicked!");
}
for (int i = 0; i < 20; i++) {
premiumticket[i] = new CheckBox();
premiumticket[i].OnCheckChanged += new EventHandler( Checkbox_CheckedChange );
...
}

Dynamically Create events for Each Checkbox and put ur alert code on it

var checkBox = new CheckBox { ID = "WCCheckBox" + item.ItemID.ToString(), ItemID = item.ItemID, Checked = item.UserValue == "1", CssClass = "wounditem" };
Your implementation may be another.

Add this to your for loop:
premiumticket[i].OnCheckChanged += new EventHandler( premiumTicketChanged );
Checkbox toggled handler:
public void premiumTicketChanged (Object sender, EventArgs e)
{
int ticketCount = premiumticket.Count(c => c.Checked);
MessageBox.Show( string.Format("You have checked {0} checkboxes....", ticketCount));
}

After you add dynamically a control you can use AddHandler to manage the events of this control.
Remember set the checkbox autopostback property to true.

Related

How to add a click event to dynamically created labels

Label[] l1 = new Label[30];
DataTable dt = ConsoleApp2.CitiesDB.getCities(this.region);
foreach(DataRow row in dt.Rows)
{
count++;
string city = row.Field<string>("city");
l1[count] = new Label();
l1[count].Location = new System.Drawing.Point(x,y);
l1[count].Size = new Size(140, 80);
l1[count].Font = new System.Drawing.Font("Century Gothic", 8.5F);
l1[count].Text = city;
x = x + 260;
this.Controls.Add(l1[count]);
this.Refresh();
if(count == 4 || count %4 ==0)
{
y = y + 150;
x = 40;
}
//l1[count].Click += new EventHandler(l1_click);
}
So i made a dynamic labels (each label is a city name). how can i make each label clickable? i have a register form - what i want is if user clicks on "new york" then in the "city" textbox it will appear. the way with the EventHandler doesnt works for me);. what can i do?
what i mean in code that doesnt work:
protected void l1_click(object sender, EventArgs e)
{
RegisterForm register = new RegisterForm(username,email,password,address,phone);
register.state.Text = region;
register.city.Text = l1[count].Text;
register.Show();
}
thanks (:
Assign one click event for each label (dynamically created):
l1[count].Click += l1_click;
In the one click event use the sender argument to see which label was clicked on:
protected void l1_click(object sender, EventArgs e)
{
Label lbl = (Label)sender;
MessageBox.Show(lbl.Text);
}

Reference a button outside of a loop?

This function dynamically creates nine buttons for use in a game I am making. You can see what attributes I give to the button.
private void createbuttons()
{
int tot = 0;
int x = 100;
int y = 100;
while(tot < 9)
{
string buttonsname = (tot + "button").ToString();
Button creating = new Button();
creating.Name = buttonsname;
creating.Size = new Size(100, 100);
creating.Click += delegate
{
MessageBox.Show("You clicked me!");
};
creating.Text = buttonsname;
if(x > 300)
{
y += 100;
x = 100;
}
creating.Location = new Point(x, y);
Controls.Add(creating);
tot += 1;
x += 100;
}
}
What I want to know is how to reference these buttons in different parts of the same form. Specifically when 'Start Game' is clicked I want to change the text for each button to something different.
private void button10_Click(object sender, EventArgs e)
{
//What would I write here to change the text?
}
You can access the buttons by enumerating the controls, or you could create a list of buttons for future reference, and use that list later.
Here is how you do it with a list:
private IList<Button> addedButtons = new List<Button>();
private void createbuttons() {
int tot = 0;
int x = 100;
int y = 100;
while(tot < 9) {
string buttonsname = (tot + "button").ToString();
Button creating = new Button();
creating.Name = buttonsname;
creating.Size = new Size(100, 100);
creating.Click += delegate {
MessageBox.Show("You clicked me!");
};
creating.Text = buttonsname;
if(x > 300) {
y += 100;
x = 100;
}
creating.Location = new Point(x, y);
addedButtons.Add(creating); // Save the button for future reference
Controls.Add(creating);
tot += 1;
x += 100;
}
}
Now you can do this:
foreach (var btn : addedButtons) {
btn.Text = "Changed "+btn.Text;
}
The form has a property Controls that holds all child controls. To find a child control by its Name property use method Find, which returns the array, because there may be several control with the same Name, but if you make sure that names exist, are unique, and you know their type (Button) you can just take the first item from the array and cast it:
private void button10_Click(object sender, EventArgs e)
{
Button buttonNamedFred = (Button)this.Controls.Find("Fred", false)[0];
buttonNamedFred.Text = "I'm Fred";
}

Adding Event Handler for Dynamically Created to window Form

I have a window form where I am creating a list of Checkboxes. The number of checkboxes created are based upon how many items are returned from the database. I've been able to create the checkboxes; however, I am not sure how to add event handlers for these checkboxes. For example, I'd like to add an OnCheckedChanged or CheckStateChanged event. How can I add these events? Also, I would appreciate any other suggestion. I am a total newbie to programming.
private void Form1_Load(object sender, EventArgs e)
{
CheckBoxes = new CheckBox[listGroup.Count()];
for (int i = 0; i < listGroup.Count(); i++)
{
CheckBoxes[i] = new CheckBox();
CheckBoxes[i].Text = listGroup.ElementAt(i).GroupName;
CheckBoxes[i].Name = "txt" + listGroup.ElementAt(i).GroupName.Replace(' ', '_');
CheckBoxes[i].CheckedChanged += new EventHandler(CheckBoxes[i]+"_CheckedChanged");
CheckBoxes[i].Width = 200;
if (i == 0)
{
CheckBoxes[i].Location = new System.Drawing.Point(5, 10);
}
else if (i == 1)
{
CheckBoxes[i].Location = new System.Drawing.Point(5, 40);
}
else if (i == 2)
{
CheckBoxes[i].Location = new System.Drawing.Point(5, 80);
}
this.Controls.Add(CheckBoxes[i]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
//...
CheckBoxes[i].CheckedChanged += checkBoxes_CheckedChanged;
CheckBoxes[i].CheckStateChanged += checkBoxes_CheckStateChanged;
}
void checkBoxes_CheckedChanged(object sender, EventArgs e)
{ //do stuff when checked changed }
void checkBoxes_CheckStateChanged(object sender, EventArgs e)
{ //do stuff when check state changed }
Note: this will give identical event handling for all of your checkboxes.
If you want to do different things for different textboxes, you have to name the eventhandler differently and define that eventhandler.
A more efficient way to set the location of your checkboxes
for (int i = 0; i < listGroup.Count(); i++)
{
CheckBoxes[i] = new CheckBox();
CheckBoxes[i].Text = listGroup.ElementAt(i).GroupName;
CheckBoxes[i].Name = "txt" + listGroup.ElementAt(i).GroupName.Replace(' ', '_');
CheckBoxes[i].CheckedChanged += new EventHandler(CheckBoxes[i] + "_CheckedChanged");
CheckBoxes[i].Width = 200;
//set location based on index of i
CheckBoxes[i].Location = new System.Drawing.Point(5, 10 + (i * 30));
this.Controls.Add(CheckBoxes[i]);
}
private void LoadNewCheckboxes()
{
dynamic listGroupCount = 10;
List<System.Windows.Forms.CheckBox> CheckBoxes = new List<System.Windows.Forms.CheckBox>();
for (int i = 0; i <= listGroupCount - 1; i++)
{
System.Windows.Forms.CheckBox chkbox = new System.Windows.Forms.CheckBox();
chkbox.Text = i.ToString();
//listGroup.ElementAt(i).GroupName
chkbox.Name = "txt" + i.ToString();
//listGroup.ElementAt(i).GroupName.Replace(" "c, "_"c)
chkbox.CheckedChanged += new EventHandler(chkbox_CheckedChanged);
chkbox.CheckStateChanged += new EventHandler(chkbox_CheckStateChanged);
chkbox.Width = 200;
chkbox.AutoSize = true;
this.Controls.Add(chkbox);
CheckBoxes.Add(chkbox);
if (i == 0)
{
chkbox.Location = new System.Drawing.Point(5, 10);
}
else
{
chkbox.Location = new System.Drawing.Point(5, (CheckBoxes[i - 1].Top + CheckBoxes[i - 1].Height + 10));
}
}
}
private void chkbox_CheckedChanged(object sender, EventArgs e)
{
System.Windows.Forms.CheckBox chkbox = (System.Windows.Forms.CheckBox)sender;
if (chkbox != null)
{
//do somthing
Debug.WriteLine("chkbox_CheckedChanged");
Debug.WriteLine(chkbox.Text);
Debug.WriteLine(chkbox.Checked.ToString());
Debug.WriteLine(chkbox.Name.ToString());
}
}
private void chkbox_CheckStateChanged(object sender, EventArgs e)
{
System.Windows.Forms.CheckBox chkbox = (System.Windows.Forms.CheckBox)sender;
if (chkbox != null)
{
//do somthing
Debug.WriteLine("chkbox_CheckStateChanged");
Debug.WriteLine(chkbox.Text);
Debug.WriteLine(chkbox.Checked.ToString());
Debug.WriteLine(chkbox.Name.ToString());
}
}

Array of buttons: change property

I have an array of buttons, like this:
int x = 0, y = 0;
butt2 = new Button[100];
for (int i = 0; i < 100; i++)
{
butt2[i] = new Button();
int names = i;
butt2[i].Name = "b2" + names.ToString();
butt2[i].Location = new Point(525 + (x * 31), 70 + (y * 21));
butt2[i].Visible = true;
butt2[i].Size = new Size(30, 20);
butt2[i].Click += new EventHandler(butt2_2_Click); //problem lies here (1)
this.Controls.Add(butt2[i]);
}
private void butt2_2_Click(object sender, EventArgs e)
{
// want code here
}
I want to change the back color of the button when clicked. I was thinking of passing i to be able to do this:
butt2[i].BackColor = Color.Green;
This should do the trick:
private void butt2_2_Click(object sender, EventArgs e)
{
Button pushedBtn = sender as Button;
if(pushedBtn != null)
{
pushedBtn.BackColor = Color.Green;
}
}
And this holds for most UI events, the 'object sender' parameter refers to the control that 'sent'/'fired' the event.
To learn more about C# event handling, I would start here.
Also, here is a SO question about GUI event handling, answered nicely by Juliet (accepted answer).
Hope this helps.

Dynamically Created Combobox's SelectedIndexChanged Event

i'm designing a windows form application. In this app, user selects a number from a combobox, then depending on the number, some dynamic controls will be created(labels and comboboxes).
My problem is, i need to write some code on these dynamically created comboboxs' "selectedindexchanged" event. But i don't know how to create an event to dynamic combobox.
Here is my function:
FORM1.CS
public void getchildCntrl(Panel pnl,ComboBox cmbb)
{
for (int ix = pnl.Controls.Count - 1; ix >= 0; ix--)
if (pnl.Controls[ix].Name.Substring(0, 5) == "Child") pnl.Controls[ix].Dispose();
if (cmbb.SelectedIndex != 0)
{
Label[] childLabels = new Label[cmbb.SelectedIndex];
ComboBox[] txtTeamNames = new ComboBox[cmbb.SelectedIndex];
for (int i = 0; i < txtTeamNames.Length; i++)
{
//label create
var lbl = new Label();
childLabels[i] = lbl;
lbl.Name = "ChildLb" + i.ToString();
lbl.Text = (i + 1).ToString() + ". Çocuk-Yaş :";
lbl.Width = 80;
lbl.Location = new Point(cmbb.Location.X - 85, cmbb.Location.Y + 7 + ((i + 1) * 28));
lbl.Visible = true;
pnl.Controls.Add(lbl);
//combobox create
var cmb = new ComboBox();
txtTeamNames[i] = cmb;
cmb.Name = "Child" + i.ToString();
cmb.Location = new Point(cmbb.Location.X, cmbb.Location.Y + 5 + ((i + 1) * 28));
cmb.Width = 40;
cmb.DropDownStyle = ComboBoxStyle.DropDownList;
cmb.DataSource = ages.ToArray();
cmb.Visible = true;
pnl.Controls.Add(cmb);
}
}
}
You just register to the event like below...
cmb.SelectedIndexChanged += new System.EventHandler((object o, EventArgs e) =>
{
//Do something here
});
Or
cmb.SelectedIndexChanged += new System.EventHandler(cmb_SelectedValueChanged);
private void cmb_SelectedValueChanged(object sender, EventArgs e)
{
//Do something here.
}
You can hook up an event handler to the ComboBox like this:
cmd.SelectionChanged += new SelectionChangedEventHandler(GuiController_SelectionChanged);
void GuiController_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
throw new NotImplementedException();
}
Register event handler this way:
cmb.SelectedIndexChanged+=new EventHandler(cmb_SelectedIndexChanged);
Unregister this way:
cmb.SelectedIndexChanged-=new EventHandler(cmb_SelectedIndexChanged);
private void cmb_SelectedIndexChanged(object sender, System.EventArgs e)
{
//write your event code here
}
How to: Create Event Handlers at Run Time for Windows Forms
public void getchildCntrl(Panel pnl,ComboBox cmbb)
{
//// your code.....
//combobox create
var cmb = new ComboBox();
cmb.SelectedIndexChanged+=new EventHandler(cmb_SelectedIndexChanged);
// remaining code
cmb.Visible = true;
pnl.Controls.Add(cmb);
}
}
}
For specifying parameters - go through:
ComboBox.SelectedIndexChanged Event

Categories

Resources