动态生成复选框,但事件处理程序仅适用于最后一个

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

我正在尝试使用事件处理程序动态创建复选框,但事件处理程序仅适用于最后生成的复选框..

我试图改变我的代码的位置。我也尝试制作更多的复选框来确定是否会有任何不同。

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

我想知道如何更改代码以便每个复选框都有此事件处理程序..

这段代码应该可以达到 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( );
        }
    }
}

我还建议缩短和简化部分代码,例如。

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

尽量减少代码,避免使用box.Property来设置一些要设置的数据none。