Strider007
Strider007

Reputation: 4945

cant remove an item from listbox

I am trying to remove an item from listbox but is not working. even that im sure that there exist an item to remove. any idea about what maybe going wrong?

iSelectedItem = ContactConflictListBox.ItemIndex;


if ((iSelectedItem == -1))
{
    return;
}

ContactConflictListBox.Items.Remove(iSelectedItem);

Upvotes: 2

Views: 1584

Answers (3)

Femaref
Femaref

Reputation: 61437

You are getting an index, not an item. To remove by index, use ContactConflictListBox.Items.Remove(ContactConflictListBox.Items[iSelectedItem]); or ContactConflictListBox.Items.RemoveAt(iSelectedItem);. Be aware, that the RemoveAt method shouldn't be used in code, it's just there for infrastructural reasons.

Upvotes: 4

etc
etc

Reputation: 630

if (ListBox.SelectedItem!= null)
{
    ListBox.Items.Remove(ListBox.SelectedItem); 
}

Upvotes: 3

OregonGhost
OregonGhost

Reputation: 23759

ListBox.ObjectCollection.Remove takes the object you want to remove as argument. You have to either call ListBox.ObjectCollection.RemoveAt (which is, unfortunately, documented as infrastructure-only), or pass the object to ListBox.ObjectCollection.Remove:

ContactConflictListBox.Items.Remove(ContactConflictListBox.Items[iSelectedItem]);

(or, in case the index is not relevant:)

ContactConflictListBox.Items.Remove(ContactConflictListBox.SelectedItem);

Upvotes: 1

Related Questions