Listbox behavior

John Pike 1 Reputation point
2023-05-18T18:00:40.1233333+00:00

I have a CheckedListBox and a ListBox. When someone selects an item in the CheckedListBox, it shows up in the ListBox Item List. I also want to be able to remove items from the ListBox which will cause the item in the CheckedListBox to be unselected. I have been successful in adding items to the ListBox from the CheckedListBox when selected. I am having trouble removing items from the Listbox and unselecting them from the CheckedListBox. The strange thing is that it works when I remove the item from the ListBox. When I try to unselect the item from the CheckedListBox, it causes the ListBox to leave ghost items in the ListBox. I am including the code I use for removing the item from the ListBox. When I comment out the code to uncheck the CheckedListBox, it works correctly, When I uncomment this code, it does not work correctly. Help!!!

            string PlayerRemoved;
            int itemcount;
            int itemindex;
            int nbrply;

            itemcount = SelectedPlayersListBox.Items.Count;
            itemindex = SelectedPlayersListBox.SelectedIndex;

            // Get the player selected.
            PlayerRemoved = SelectedPlayersListBox.Text;
            // Make sure that the player is not null.
            if (PlayerRemoved != null)
            {
                // Remove the Player from the list.
                SelectedPlayersListBox.Items.Remove(PlayerRemoved);
                // Get the index of the Player removed from the Available List.
				

//These are the two lines of code that cause the ListBox to behave incorrectly.
                //itemindex = AvailablePlayerListBox.Items.IndexOf(PlayerRemoved);
                // Uncheck the box next to the Players name.
                //AvailablePlayerListBox.SetItemChecked(itemindex, false);
            }


            // Reduce the number of players by one.
            nbrply = Int32.Parse(NbrofPlayers.Text);
            nbrply -= 1;
            NbrofPlayers.Text = nbrply.ToString();
            NbrofPlayers.Refresh();

            SelectedPlayersListBox.Refresh();
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,869 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,629 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Jiale Xue - MSFT 42,816 Reputation points Microsoft Vendor
    2023-05-19T07:00:22.8866667+00:00

    Hi @John Pike , Welcome to Microsoft Q&A.

    Just use the correct logic in the checklistbox: add when checked, remove when unchecked.

    button1, button2 are remove and removeAll respectively.

    private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        var selectItem = checkedListBox1.SelectedItem;
        bool isChecked = checkedListBox1.GetItemChecked(checkedListBox1.SelectedIndex);
        if (!isChecked)
        {
            listBox1.Items.Add(selectItem);
        }
        else
        {
            listBox1.Items.Remove(selectItem);
        }
        //Get the correct amount at now
        BeginInvoke(new Action(() =>
        {
            textBox1.Text = checkedListBox1.CheckedItems.Count.ToString();
        }));
    }
    
    private void button1_Click(object sender, System.EventArgs e)
    {
        if (listBox1.SelectedItem == null)
            return;
        var item = listBox1.SelectedItem;
        int index = checkedListBox1.Items.IndexOf(item);
        checkedListBox1.SelectedItem = item;
        checkedListBox1.SetItemChecked(index, false);
        textBox1.Text = checkedListBox1.CheckedItems.Count.ToString();
    }
    
    private void button2_Click(object sender, System.EventArgs e)
    {
        for (int i = checkedListBox1.Items.Count - 1; i >= 0; i--)
        {
            checkedListBox1.SetItemChecked(i, false);
        }
        listBox1.Items.Clear();
        textBox1.Text = checkedListBox1.CheckedItems.Count.ToString();
    }
    

    enter image description here

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Karen Payne MVP 35,386 Reputation points
    2023-05-25T10:55:57.2933333+00:00

    If you are still looking for a solution these extension methods can help but have not included how to use them but can if still need a solution.

    public static class CheckedListBoxExtensions
    {
        /// <summary>
        /// Get checked items as <see cref="T"/>
        /// </summary>
        /// <typeparam name="T">Model</typeparam>
        /// <param name="sender">CheckedListBox</param>
        /// <returns>List if one or more items are checked</returns>
        public static List<T> CheckedList<T>(this CheckedListBox sender)
            => sender.Items.Cast<T>()
                .Where((item, index) => sender.GetItemChecked(index))
                .Select(item => item)
                .ToList();
    
        /// <summary>
        /// Get all <typeparamref name="T"/> items
        /// </summary>
        /// <param name="sender">CheckedListBox</param>
        /// <returns></returns>
        public static List<CheckedData<T>> IndexList<T>(this CheckedListBox sender) =>
        (
            from item in sender.Items.Cast<T>()
                .Select(
                    (model, index) =>
                        new CheckedData<T>
                        {
                            Index = index,
                            Model = model
                        }
                )
                .Where((x) 
                    => sender.GetItemChecked(x.Index))
            select item
        ).ToList();
    
        /// <summary>
        /// Uncheck all items
        /// </summary>
        /// <param name="sender">CheckedListBox</param>
        public static void UnCheckAll(this CheckedListBox sender)
        {
            foreach (int index in sender.CheckedIndices)
            {
                sender.SetItemCheckState(index, CheckState.Unchecked);
            }
        }
    
        /// <summary>
        /// Find item, set check state for <see cref="T"/>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sender">CheckedListBox</param>
        /// <param name="text">text to locate case insensitive</param>
        /// <param name="checked">set check state to</param>
        public static void SetChecked<T>(this CheckedListBox sender, string text, bool @checked)
        {
            var result = sender.Items.Cast<T>().Select((item, index) => 
                new
                {
                    Item = item as IBase, 
                    Index = index
                })
                .FirstOrDefault(@this => 
                    string.Equals(@this.Item!.Name, text, StringComparison.CurrentCultureIgnoreCase));
    
            if (result != null)
            {
                sender.SetItemChecked(result.Index, @checked);
            }
        }
    }
    
    
    
    
    0 comments No comments