Lebron11 Lebron11 - 1 month ago 6
C# Question

ListBox won't remove the first item in c#

private void button_Click(object sender, RoutedEventArgs e) //ADD
{
listBox.Items.Add("some");
listBox.Items.Add("text");

}


private void button1_Click(object sender, RoutedEventArgs e) //DELETE
{

if (!(listBox.SelectedIndex == -1))
listBox.Items.Remove(listBox.SelectedItem);
else
System.Windows.MessageBox.Show("You have not selected an item");

}


The ListBox won't delete sometimes the first item. The reason is that after i delete an item a white border appears on the previous item. I don't know why this border appears. See Image to see what I mean. When the whit border appears and I try to delete the first item it says that i have not select an item... IF I SAVE 3 TIMES THE SAME ITEM AND DELETE THE SECOND THE BUG APPEARS TRY IT OUT for example some, some,some

enter image description here

Answer

Try removing the item from its position rather than the item itself. I found doing it no longer selects another item as the focus is completely removed from the listbox.

private void button1_Click(object sender, RoutedEventArgs e)
{
   if (listBox.SelectedIndex != -1)
      listBox.Items.RemoveAt(listBox.SelectedIndex);

   else
      System.Windows.MessageBox.Show("You have not selected an item");

}