none
listbox item checked RRS feed

  • Question

  • I'm using a listbox with several check boxed items listed.

    When I click the listbox I need to determine if the selected item is checked already.

    If it is then uncheck it - if it isn't then check it.

    My code...

                            

                    bool bool_adders = lstbx_TMDAdders.GetItemChecked(0);  // is item index 0 checked?
                    switch (bool_adders)
                    {
                        case true: //box is already checked
                            lstbx_TMDAdders.SetItemChecked(0, false);  // this should uncheck the box but doesn't.
                            break;
                        case false: //box is not already checked
                            lstbx_TMDAdders.SetItemChecked(0, true);  //this will check the box
                            break;

                    }

    Am I doing something wrong? obviously so because it isn't working.

    Using VS 2015 C#

    Let me know.


    tac

    Wednesday, January 2, 2019 8:11 PM

All replies

  • Hello,

    Sounds like you are working with a CheckedListBox not a ListBox. You can subscribe to the following event ItemCheck.

    checkedListBox1.ItemCheck += CheckedListBox1_ItemCheck;

    Then

    private void CheckedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (e.CurrentValue == CheckState.Checked)
        {
            // do something
        }
        else if (e.CurrentValue == CheckState.Unchecked)
        {
            // do something else
        }          
    }

    To see everything (including what the current value is going to be)

    private void CheckedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (e.CurrentValue == CheckState.Checked)
        {
            // do something
        }
        else if (e.CurrentValue == CheckState.Unchecked)
        {
            // do something else
        }          
        Console.WriteLine($"{checkedListBox1.Text} Currently {e.CurrentValue} Going to be {e.NewValue}");
    }
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Wednesday, January 2, 2019 8:24 PM
    Moderator