Search code examples
c#winformscheckedlistbox

CheckedListBox updates checkedItems very slow


I am using a CheckedListBox in my C# software. The software checks and unchecks items as well as the user by the graphical interface. I added a button to uncheck all items. When the user presses a button, the software should uncheck all items. Sometimes, when I uncheck the items by software after the button click, some items still appear in the checked items property of the listbox. Is it possible that the CheckedListBox needs some time to update the CheckedItems property? Or is something wrong with my Invoke-Usage?

I found out, that when I set a breakpoint in between the unchecking and the reading of the checked item, the checked items are updated properly.

//---------------------------------------------
// function to get the checked items
//---------------------------------------------
public List<object> getCheckedItems() {
    var returnedItems = new List<object>();
    var checkedItems = checkedListBox.CheckedItems;
    var iterator = checkedItems.GetEnumerator();
    while ( iterator.MoveNext() )
        returnedItems.Add( iterator.Current );

    return returnedItems;
} 

//---------------------------------------------
// function to uncheck an item
//---------------------------------------------
public void uncheckItem( object item ) {
    if ( containsItem( item ) ) {
        int index = checkedListBox.Items.IndexOf( item );
        if ( checkedListBox.InvokeRequired ) {
            var uncheckInvoker = 
                new MethodInvoker( () => checkedListBox.SetItemChecked( index, false ) );
            checkedListBox.BeginInvoke( uncheckInvoker );
        }
        else
            checkedListBox.SetItemChecked( index, false );

        // the following two line are added for debugging
        var items = checkedListBox.CheckedItems; // breakpoint here
        Console.WriteLine( "number of checked items = " + items.Count );
    }
    else 
        throw new ArgumentException( "Item " + item + " is not available" );
}

//---------------------------------------------
//client code
//---------------------------------------------
var checkedItems = subTestListBox.getCheckedItems();
foreach ( var checkedItem in checkedItems )
    subTestListBox.uncheckItem( checkedItem );

I expect that the checkedItems property is updated right after I called the SetItemChecked( int, bool ) function.


Solution

  • Simplify?

    private void UncheckAll(CheckedListBox clb)
    {
        if (clb.InvokeRequired)
        {
            clb.Invoke((MethodInvoker)delegate {
                UncheckAll(clb);
            });
        }
        else
        {
            for(int i = 0; i < clb.Items.Count; i++)
            {
                if (clb.GetItemChecked(i))
                {
                    clb.SetItemChecked(i, false);
                }
            }                
        }
    }