HelpNeeder HelpNeeder - 3 months ago 17
C# Question

How to prevent SelectedIndexChanged event from firing in ListBox after removing an item from it

I am working on selecting an item which will cause deletion of selected item. The problem is that when I delete an item I am selecting additional item which cause another deletion...

How do I unselest/deselect after deleting selected item?

This causes my problem:

void lbMessage_SelectedIndexChanged(object sender, EventArgs e)
{
DialogResult result = new DialogResult();

result = MessageBox.Show("Are you sure you want to remove this item?", "Removal Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

if (result == DialogResult.Yes)
{
lbMessage.Items.Remove(lbMessage.SelectedItem);
lbMessage.SelectedIndex = -1;
}
else
{
}
}

private void btnAddMessage_Click(object sender, EventArgs e)
{
lbMessage.Items.Add(txtMessage.Text);
txtMessage.Text = string.Empty;
}

Answer

Try removing the SelectedIndexChanged event before removing the item, then add it back in:

private void lbMessage_SelectedIndexChanged(object sender, EventArgs e) {
  if (MessageBox.Show("Are you sure you want to remove this item?", 
                      "Remove Confirmation", 
                      MessageBoxButtons.YesNo,
                      MessageBoxIcon.Question) == DialogResult.Yes) {
    lbMessage.SelectedIndexChanged -= lbMessage_SelectedIndexChanged;
    lbMessage.Items.Remove(lbMessage.SelectedItem);
    lbMessage.SelectedIndexChanged += lbMessage_SelectedIndexChanged;
  }
}