Deleting the selected item from the list

advertisements

Basically it's a contact list, select the contact from the listbox and hit the remove button, deleting it from the list.

        private void btnRmv_Click(object sender, EventArgs e)
    {

        try{

        listBox.Items.Remove(listBox.SelectedItems[0]);

        people.RemoveAt(listBox.SelectedIndex);

        }
        catch { }
    }

This code seems to delete the Contacts from the listbox, but if I save my program and open it up again, the contact is back there. I am saving all the contacts in an Xml file. The program auto saves on exit, and does have a manual save button.

Thanks


You don't show where your code is to save, but I imagine there is one contact missing - probably the one under the contact you wanted to remove?

Since you are using SelectedIndex AFTER removing the item from the list box, then some other item must be selected.

Try reversing the order:

private void btnRmv_Click(object sender, EventArgs e)
{
    try
    {
        people.RemoveAt(listBox.SelectedIndex);
        listBox.Items.Remove(listBox.SelectedItems[0]);
    }
    catch { }
}