TheAdnan
TheAdnan

Reputation: 19

How to remove an item from a listbox and a list of objects in C#

I wanted to delete a selected item from the listbox, and after that, to remove the object which was referenced to that item I wanted to remove. I tried the following

private void Remove_candidate_Click(object sender, EventArgs e)
        {
            int i = candidate_list.SelectedIndex; // candidate_list is the ListBox
            if (candidate_list.SelectedItems.Count > 0) candidate_list.Items.Remove(candidate_list.SelectedItem);
            candidates.RemoveAt(i); //candidates is the object list
        }

When I start the application, it crushes after clicking on the "Remove" button.

Upvotes: 2

Views: 486

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

In general case, when many items can be selected you can use this code to remove all the selected items:

  // To prevent candidate_list repainting while items updating
  candidate_list.BeginUpdate();

  try {
    // When using RemoveAt() one should use backward loop 
    for (int i = candidate_list.SelectedIndices.Count - 1; i >= 0; --i) {
      int index = candidate_list.SelectedIndices[i];

      candidate_list.Items.RemoveAt(index);
      candidates.RemoveAt(index); 
    }
  }
  finally {
    candidate_list.EndUpdate();
  }

Upvotes: 1

Andrew
Andrew

Reputation: 2325

Just use

if (candidate_list.SelectedItems.Count > 0) candidate_list.Items.RemoveAt(i);

More robust way of doing this

int i = candidate_list.SelectedIndex; // candidate_list is the ListBox
if (i >= 0) 
{
    candidate_list.Items.RemoveAt(i);
    candidates.RemoveAt(i); //candidates is the object list
}

Upvotes: 1

Related Questions