Home > Back-end >  i can't remove the index in list box
i can't remove the index in list box

Time:04-19

I'm trying to remove to selected index in my Listbox but I get an error:

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')

Please help me, I'm a newbie to C#.

public void listBoxName_SelectedIndexChanged(object sender, EventArgs e)
{
    int index = listBoxName.SelectedIndex;
    labelName.Text = clients[index].Name;
    labelAge.Text = clients[index].Age.ToString();
    labelPhone.Text = clients[index].Phone;
    labelAddress.Text = clients[index].Address;
}

private void buttonClearFields_Click(object sender, EventArgs e)
{
    textBoxName.Text = "";
    textBoxAge.Text = "";
    textBoxPhone.Text = "";
    textBoxAddress.Text = "";
}

private void buttonRemove_Click(object sender, EventArgs e)
{
    listBoxName.Items.RemoveAt(listBoxName.SelectedIndex);
}

CodePudding user response:

int index = listBoxName.SelectedIndex;
if (index < 0 || index > clients.Length) return;

CodePudding user response:

có 2 chỗ để sách thôi đừng xin quyển thứ ba

  •  Tags:  
  • c#
  • Related