通过if和else从c#中的llist框中删除项目

时间:2018-03-13 19:25:19

标签: c# listbox listboxitems

我正在做一个需要从列表框中删除项目的练习... 我已经知道如何一个接一个地同时做到这一点。

我想知道怎么做:如果选择了一个项目,只删除该项目,否则全部删除。

我尝试了一会儿,我无法弄清楚。

1 个答案:

答案 0 :(得分:0)

解决

 private void btnDelete_Click(object sender, EventArgs e)
 {

    listBox.Items.RemoveAt(listBox.SelectedIndex);

    listBox.Items.Clear();
 }        

我正在考虑在“If and Else”中使用这两行,但我意识到它与“Try and Catch”一起使用,如:

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