Delete items from a llist box in c# through if and else

44 Views Asked by At

I'm doing an exercise where I need to delete items from a listbox... I already know how to do it one by one and all at the same time.

I was wondering how to do it like: if an item were selected, delete only that item, else delete all.

I'm trying for a little while and I can't figure it out.

1

There are 1 best solutions below

0
Igor Simões On

SOLVED

 private void btnDelete_Click(object sender, EventArgs e)
 {

    listBox.Items.RemoveAt(listBox.SelectedIndex);

    listBox.Items.Clear();
 }        

I was thinking on use these two lines in an "If and Else" but I realize that works with "Try and Catch", like:

try
{
    listBox.Items.RemoveAt(listBox.SelectedIndex);
}
catch (Exception)
{
    listBox.Items.Clear();
}