如何在动态创建的winform控件上引发动态创建的事件?

时间:2013-03-19 22:23:19

标签: c# winforms

我有一个CheckedListBox控件,我是从下面以编程方式创建的......

Button btnSelectAll = new Button();
btnSelectAll.Text = "Select All";
btnSelectAll.Name = item.Id;
btnSelectAll.Tag = param.Id;
CheckedListBox chkListBox = new CheckedListBox();
chkListBox.Size = new System.Drawing.Size(flowPanel.Size.Width - lblListBox.Size.Width - 10, 100);
//set the name and tag for downstream event handling since two-way bindings are not possible with control
chkListBox.Tag = param.Id;
chkListBox.Name = item.Id;
chkListBox.ItemCheck += new ItemCheckEventHandler(chkListBox_ItemCheck);
btnSelectAll.Click += new EventHandler(btnSelectAll_Click);

注意当我动态创建项目时,每当命中chkListBox上的ItemCheck时,我还添加了一个事件处理程序。代码中的其他地方......我做......

CheckedListBox tmpCheckedListBox = cntrl as CheckedListBox;
for (int i = 0; i < tmpCheckedListBox.Items.Count; i++)
{
   tmpCheckedListBox.SetItemChecked(i, true);
}

当我执行上述操作时,它不会引发ItemChecked事件。如何举起此事件,好像用户点击了该项?

1 个答案:

答案 0 :(得分:2)

一种方法是调用与分配给事件相同的方法,并为发送者传递正确的控制,例如:

for (int i = 0; i < tmpCheckedListBox.Items.Count; i++)
{
   tmpCheckedListBox.SetItemChecked(i, true);
   chkListBox_ItemCheck(tmpCheckedListBox.Items[i],null);
}

您通常可以通过传递EventArgs.Emptynull作为事件参数,但是如果您在事件处理程序中依赖它们,则需要构造正确的参数类并将其传递给,例如:

for (int i = 0; i < tmpCheckedListBox.Items.Count; i++)
{
   var args = new ItemCheckEventArgs(i,true,tmpCheckedListBox.GetItemChecked(i));

   tmpCheckedListBox.SetItemChecked(i, true);
   chkListBox_ItemCheck(tmpCheckedListBox.Items[i],args);
}