2012-06-26 48 views
0

我想创建一个if语句来识别哪个字符串已从特定列表框中删除。我想我可以做一些类似下面的一个if语句,并得到它的工作,但它告诉我,它具有无效arguements - 如果有人能指导我会赞赏如何将selectedIndex与listBox中的字符串进行比较

private void button2_Click(object sender, EventArgs e) 
    { 

     listBox2.Items.RemoveAt(listBox2.SelectedIndex); 
     if(listBox2.Items.RemoveAt(listBox2.SelectedItems.ToString().Equals("Test"))) 
     { 
     picturebox.Image = null; 
     } 
    } 

回答

3

您需要检查SelectedItem将其取出:

private void button2_Click(object sender, EventArgs e) 
{ 
    if (listBox2.SelectedIndex != -1) 
    { 
     if (listBox2.SelectedItem.ToString().Equals("Test"))) 
      picturebox.Image = null; 

     listBox2.Items.RemoveAt(listBox2.SelectedIndex); 
    } 
} 

我还添加了一个检查,以确保该项目已实际选择(因为你会得到错误,否则)。

0

你应该这样做:

String deletedString = listBox2.Items.ElementAt(listBox2.SelectedIndex).ToString(); 
    listBox2.Items.RemoveAt(listBox2.SelectedIndex); 
    if(listBox2.Items.RemoveAt(deletedString == "Test")) 
    { 
    picturebox.Image = null; 
    } 

它可能无法编译(检查是否有物品SelectedItem属性)。

1

你的问题是你打电话给ListBox.Items.RemoveAt(int index)并传入一个布尔值:listBox2.SelectedItems.ToString().Equals("Test"))

另外,您先删除该项目,然后再次调用RemoveAt,这实际上会删除一个不同的项目(不管是现在位于该索引处)还是抛出一个异常(如果您已超出界限)你的ListBox集合。

你应该先检查您选择的项目等于“测试”,然后从你的ListBox删除的项,像这样:

private void button2_Click(object sender, EventArgs e) 
{ 
    // SelectedIndex returns -1 if nothing is selected 
    if(listBox2.SelectedIndex != -1) 
    { 
     if(listBox2.SelectedItem.ToString().Equals("Test")) 
     { 
      picturebox.Image = null; 
     } 
     listBox2.Items.RemoveAt(listBox2.SelectedIndex); 
    } 
} 
相关问题