MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37113

Add item to listbox and select it

I have a listbox (SelectionMode is set to MultiExtended as mentioned on this topic) containing one single entry: "...". When user double-clicks this a dialog appears to select a single file. When user selects one the dialog disappears and the file should be added to the list. This all works.

My problem is that I want to select only that newly added entry within my listbox. However with the following code both - the "..." and the actual file are selected:

private void lbx_DoubleClick(object sender, EventArgs e)
{
    if (this.lbx.SelectedItem == "..."
            && this.ofdReferences.ShowDialog() == DialogResult.OK
    {
        this.lbx.Items.Insert(this.lbx.SelectedIndex, this.ofdReferences.FileName);
        this.lbx.SetSelected(this.lbx.SelectedIndex - 1, true); // select newly added entry
    }
}

So I also added this line:

this.lbx.SetSelected(this.lbx.SelectedIndex, false);        // unselect ...

Now the "..."-entry is selected instead of the file.

I even tried to use SelectedIndex = this.lbxProjectReferences.SelectedIndex - 1. This also selects both entries within the list.

Upvotes: 1

Views: 1476

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37113

The SelectedIndex-property is for single-select-lists. However we can use it on multi-lists also within a double-click-events also because a double-click will implicetly select one single item setting the SelecteItem correctly.

So I used this approach that deletes the list of selected entries and adds only that entry I´m interested in.

this.lbx.Items.Insert(this.lbx.SelectedIndex, this.ofdReferences.FileName);
var idx = this.lbx.SelectedIndex;
this.lbx.SelectedIndices.Clear();
this.lbx.SelectedIndices.Add(idx - 1); 

Upvotes: 1

Related Questions