Hi, I am creating an addressbook where you can add First Name, Last Name, Address, City, State and Zip into textboxes and have them display in a listbox on the add button click event. Now I need to be able to remove the selected Item from the listbox and from the Array they are stored in. The whole program works good and I have it so that the selected item is removed from the Array I just can not get the entry to remove from the listbox display. I have tried a while statement and a for statement with no luck. Any help would be great. Thanks.
I commented out the two statements that did not work for me. The For errors saying the index is going to -1, and the while tells me that there is an unhandled null reference.
private void btnDelete_Click(object sender, EventArgs e)
{
//select record for deletion, deletes from array
adrary[SelectedIndex] = null;
for (int i = SelectedIndex; i < index; i++)
{
adrary[i] = adrary[i + 1];
}
index--;
//while (lstOutput.SelectedItems.Count > 0)
//{
// lstOutput.Items.Remove(lstOutput.SelectedItems[0]);
//}
//index--;
//ListBox.SelectedObjectCollection Obj = new ListBox.SelectedObjectCollection(lstOutput);
//for (int i = Obj.Count - 1; i >= 0; i--)
//{
// lstOutput.Items.Remove(Obj[i]);
//}
}

1 answers
If only one item at a time can be selected in the ListBox (as suggested by your array code), I'd just do:
Incidentally, if you use a List<string> (or an ArrayList) rather than an array then, when you remove an item you won't need to move all the subsequent items down a place - they'll do that automatically. Also, you won't need to keep track of how many non-null items there are in the array because the List will automatically adjust its Count property when an item is removed.
answered one year ago by:
17279
78
Thanks vulpes perfect