本文介绍了管理CheckedListBox ItemCheck事件,使其在未选中项目之前运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#窗口表单应用程序中使用 CheckedListBox .

I am using CheckedListBox in C# Window Forms Application.

我想在一项被选中或未选中之后做些事情,但是 ItemCheck 事件在该项目被选中/未选中之前运行.我该怎么办?

I want to do something after one item checked or unchecked but ItemCheck event runs before the item checked/unchecked .How can I do that?

推荐答案

直到ItemCheck事件发生后,检查状态才会更新.

The check state is not updated until after the ItemCheck event occurs.

要在检查项目后运行一些代码,应使用变通办法.

To run some codes after the item checked, you should use a workaround.

最佳选择

您可以使用此选项(感谢 Hans Passant 为此,):

You can use this option (Thanks to Hans Passant for this post):

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
    this.BeginInvoke(new Action(() =>
    {
        //Do the after check tasks here
    }));
}

另一个选项

  • 如果在ItemCheck事件的中间,您需要了解项目的状态,则应使用 e.NewValue 而不是使用 checkedListBox1.GetItemChecked(i)

如果您需要将检查索引列表传递给方法,请执行以下操作:

If you need to pass a list of checked indices to a method do this:

使用代码:

var checkedIndices = this.checkedListBox1.CheckedIndices.Cast<int>().ToList();
if (e.NewValue == CheckState.Checked)
    checkedIndices.Add(e.Index);
else
    if(checkedIndices.Contains(e.Index))
        checkedIndices.Remove(e.Index);

 //now you can do what you need to checkedIndices
 //Here if after check but you should use the local variable checkedIndices
 //to find checked indices

另一个选项

在ItemCheck事件的中间,删除ItemCheck的处理程序,SetItemCheckState,然后添加处理程序.

In middle of ItemCheck event, remove handler of ItemCheck, SetItemCheckState and then add handler egain.

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
    var control = (CheckedListBox)sender;
    // Remove handler
    control.ItemCheck -= checkedListBox_ItemCheck;

    control.SetItemCheckState(e.Index, e.NewValue);

    // Add handler again
    control.ItemCheck += checkedListBox_ItemCheck;

    //Here is After Check, do additional stuff here
}

这篇关于管理CheckedListBox ItemCheck事件,使其在未选中项目之前运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-06 00:38