How to prevent a user from selecting an item in a listbox, but still letting code select an item? Prefer not to use enabled = false

I am making a Windows Forms application with algorithms for school and I want to add some nice functionality to display that the algorithm is working well. One of those things is that when the user selects an item in one listbox, the items that are part of that one item get automatically selected in another listbox. This is done by the application.

I would like it if the user could not select another item in the listbox that is automatically monitored, but enabled = false sets the color to gray which makes the text invisible when an item is automatically selected.

Is there any other way to achieve this?

1 answer

  • answered 2020-03-31 09:00 Paul Kertscher

    What you could do is

    • When the program selects an entry in the second list, set a flag
    • When an entry in the list is selected, read that flag
    • If the flag is not set, unselect the item
    • Unset the flag

    Code wise, this equates to something like the following (please note that I would not write code like this in a real-world szenario, but to get the gist of it, it should suffice)

    private bool _valueIsSetProgrammatically = false;
    
    private void listBox1_SelectedValueChanged(object sender, EventArgs e)
    {
        this._valueIsSetProgrammatically = true;
        this.listBox2.SelectedItem = this.listBox1.SelectedItem;
    }
    
    private void listBox2_SelectedValueChanged(object sender, EventArgs e)
    {
        if (!this._valueIsSetProgrammatically)
        {
            this.listBox2.SelectedItem = null;
        }
    
        this._valueIsSetProgrammatically = false;
    }
    

    Please note that this snippet unselects the second listbox. If you'd like to retain the selected item, you could change the second method to

    private void listBox2_SelectedValueChanged(object sender, EventArgs e)
    {
        if (!this._valueIsSetProgrammatically)
        {
            this.listBox2.SelectedItem = this.listBox1.SelectedItem;
        }
    
        this._valueIsSetProgrammatically = false;
    }
    

    (Technically the flag is not needed in this case, you could simply set the SelectedItem of listBox2 to the SelectedItem of listBox1.)