Home > other >  De-select/ highlight logic for listBox WinForm C#
De-select/ highlight logic for listBox WinForm C#

Time:04-29

I'm struggling to form the logic to de-select an item when either clicking the same item again or simply clicking off the listBox (if thats possible).

Currently i've set a variable prevSelectedIndex = -2 and then in the selectedIndexChanged() method for the listBox -> i check if the list.SelectedIndex == prevSelectedIndex if thats true then i call the ClearSelected() method of list.

If false, i set prevSelectedIndex = SelectedIndex and pass the selectedIndex through to a function so that i can pre-set some input fields with the data in the item selected. However, it fails to ever remove it as i think the selectedIndexChanged() method of listbox obviously is only called when it does change rather than staying the same (for trying to de-select when clicking same item again).

Moreover, when i click within/outside list box but not on an item, i tried checking to see if output would maybe change to something other than an index such as -1 yet this does not occur.

Any help appreciated!

Thanks

CodePudding user response:

The ListBox.SelectedIndexChanged is not the right event to handle if you need to toggle the selection state of an item by mouse inputs. You need to handle the mouse events.

For example, you can handle the MouseClick event to call the IndexFromPoint method which returns the index of an item if you click over it or -1 if you click on the client area. Then, you can compare that index with a class field that stores the last selected index either by mouse or keyboard arrows and unselect the item if you get equal numbers.

Put it all together along with the other requirement

public partial class YourForm : Form
{
    private int toggleIndex = -1;

    public YourForm()
    {
        InitializeComponent();
    }

    private void yourListBox_MouseClick(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            var s = sender as ListBox;
            var i = s.IndexFromPoint(e.Location);

            if (i >= 0)
            {
                if (i == toggleIndex)
                {
                    s.SetSelected(i, false);
                    // or
                    // s.ClearSelected();
                    i = -1;
                }                
            }
            else
            {
                s.ClearSelected();
            }

            toggleIndex = i;
        }
    }

    private void yourListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        toggleIndex = yourListBox.SelectedIndex;
    }

    private void yourListBox_Leave(object sender, EventArgs e)
    {
        toggleIndex = -1;
        yourListBox.ClearSelected();
    }
}
  • Related