简体   繁体   中英

C# Indexoutofrange Arrays school project error

I have some C# code below. The problem is when I try to remove from the listed box it throws an error. I know this isn't the best way to do this. This is for school and I am only allowed to use arrays. Just looking for some input. Error is indexoutofrange. Problem occurs when trying to delete a name.

private void deletebtn_Click(object sender, EventArgs e)
{
    addressbook[lstContacts.SelectedIndex].firstnamestring = "";
    addressbook[lstContacts.SelectedIndex].lastnamestring = "";
    addressbook[lstContacts.SelectedIndex].addressstring = "";
    addressbook[lstContacts.SelectedIndex].citystring = "";
    addressbook[lstContacts.SelectedIndex].statestring= "";
    addressbook[lstContacts.SelectedIndex].zipcodestring = "";

    firstname.Text = "Add a new Contact";
    lastname.Text = "";
    streetaddy.Text = "";
    city.Text = "";
    state.Text = "";
    zipcode.Text = "";

    int listselction = lstContacts.SelectedIndex;
    string removed = "Remove Contact";
    lstContacts.Items.Insert(listselction, removed);
    lstContacts.Items.RemoveAt(listselction + 1);
    lstContacts.ClearSelected();
    lstContacts.Refresh();
}

Set a breakpoint at line

lstContacts.Items.RemoveAt(listselction + 1); 

and look which value listselction has. Then check, if .Items contains so many items. Remember that the index starts at 0 . You are probably trying to delete with an index greater or equal then ´.Items.Count - 1`.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM