Search code examples
c#winformscheckboxdynamically-generated

Dynamically generating Checkboxes but the event handler only works for the last one


Im trying to make dynamically checkboxes with a event handler but the event handler only works for the last one generated..

I have tried to change the position of my code. I have also tried to make more checboxes to se if that would make any difference.

for (int i = 0; i < appointments.TotalCount; i++) {
    lstChckBox = new List<CheckBox>();
    box = new CheckBox();
    box.Tag = i;
    box.Text = appointments.Items[i].Subject;
    box.AutoSize = true;
    box.Location = new Point(KalenderLbl.Location.X, KalenderLbl.Location.Y + 
    KalenderLbl.Height + 5 + (i * 25));

    lstChckBox.Add(box);

    box.CheckedChanged += new EventHandler(chck_CheckedChanged);

    Controls.Add(box);
  }
}


void chck_CheckedChanged(object sender, EventArgs e) {
  foreach(CheckBox item in lstChckBox) {
    if (item.Checked == true) {
      Hide();
    }
  }
}

I want to know how to change the code so every checkbox have this event handler..


Solution

  • This code should do the trick as suggested by Dmitry Bychenko.

    var lstChckBox = new List<CheckBox>( );
    for (int i = 0; i < appointments.TotalCount; i++)
    {
        box = new CheckBox( );
        box.Tag = i;
        box.Text = appointments.Items[i].Subject;
        box.AutoSize = true;
    
        box.Location = new Point( KalenderLbl.Location.X, KalenderLbl.Location.Y + KalenderLbl.Height + 5 + ( i * 25 ) );
        lstChckBox.Add( box );
    
        box.CheckedChanged += new EventHandler( chck_CheckedChanged );
    
        Controls.Add( box );
    }
    
    void chck_CheckedChanged( object sender, EventArgs e )
    {
        foreach (CheckBox item in lstChckBox)
        {
            if (item.Checked == true)
            {
                Hide( );
            }
        }
    }
    

    I would also suggest to shorten and simplify parts of your code, like.

    var lstChckBox = new List<CheckBox>( );
    var InitialYPosition = KalenderLbl.Location.Y + KalenderLbl.Height + 5;
    for (int i = 0; i < appointments.TotalCount; i++)
    {
        box = new CheckBox( ) {
            Tag = i,
            Text = appointments.Items[i].Subject,
            AutoSize = true,
            Location = new Point( KalenderLbl.Location.X, InitialYPosition + ( i * 25 ) )
        };
        lstChckBox.Add( box );
    
        box.CheckedChanged += new EventHandler( chck_CheckedChanged );
    
        Controls.Add( box );
    }
    

    Minimizing the code and avoiding the using of box.Property to set some data that is going to be set none the less.