user3184618
user3184618

Reputation: 61

dynamically added checkboxes in windows forms

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

Upvotes: 0

Views: 2121

Answers (5)

Trasgu78
Trasgu78

Reputation: 3

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.

Upvotes: 0

StevieB
StevieB

Reputation: 1000

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

Upvotes: 0

SERGEY YANCHENKO
SERGEY YANCHENKO

Reputation: 43

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

Your implementation may be another.

Upvotes: 0

Dai
Dai

Reputation: 155045

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

Upvotes: 1

Amit Bisht
Amit Bisht

Reputation: 5136

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

Upvotes: 0

Related Questions