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

C# 如何在动态创建的winform控件上引发动态创建的事件?,c#,winforms,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.S

我有一个
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);
}
CheckedListBox tmpCheckedListBox=cntrl作为CheckedListBox;
对于(int i=0;i

当我执行上述操作时,它不会引发ItemChecked事件。如何引发此事件,使其看起来就像用户单击了项目一样?

一种方法是调用分配给事件的相同方法,并将正确的控件传递给发件人,例如:

for (int i = 0; i < tmpCheckedListBox.Items.Count; i++)
{
   tmpCheckedListBox.SetItemChecked(i, true);
   chkListBox_ItemCheck(tmpCheckedListBox.Items[i],null);
}
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);
}

谢谢你的回答。这是可行的,但是根据你的建议调试后,我发现问题出在别的地方。原始的SetItemChecked方法实际上是以本机方式引发事件的。@Grant感谢我犹豫了一段时间。不,调用SetItemChecked()肯定会引发ItemChecked事件。有些东西坏了,看不见什么。