【问题标题】:Dynamically generating Checkboxes but the event handler only works for the last one动态生成复选框,但事件处理程序仅适用于最后一个
【发布时间】:2019-10-14 22:42:22
【问题描述】:

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

我试图改变我的代码的位置。我还尝试制作更多的复选框以查看是否会有所作为。

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

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

【问题讨论】:

  • lstChckBox = new List&lt;CheckBox&gt;(); 退出循环
  • (sender as CheckBox)代替lstChckBox
  • 感谢@DmitryBychenko 成功了!!
  • 有谁知道如何从检查到字符串的项目中获取约会正文?

标签: c# winforms checkbox dynamically-generated


【解决方案1】:

这个代码应该按照 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 来设置一些将要设置的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2012-10-19
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多