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
Try to remove from the "people" first and then remove it from the list box or else take the selected index to a parameter. sample code is pasted below
try
{
int _SeletedIndex = listBox.SelectedIndex();
listBox.Items.Remove(listBox.SelectedItems[0]);
people.RemoveAt(_SeletedIndex);
}
catch { }
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 { }
}
You are removing selected item
first, so you lose the selected index and no item is deleted in list people
.
Lets reorder the lines:
people.RemoveAt(listBox.SelectedIndex);
listBox.Items.Remove(listBox.SelectedItems[0]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.