2016-03-21 45 views
0

我試圖在列表框中查找字符串。如果它發現顯示一個消息框,如果不是它會拋出一個不同的消息框。但即時通訊錯誤的部分。請幫忙。從列表框中讀取時出錯

{  
    string myString = metroTextBox1.Text;//username 
    // Search starting from index -1: 
    int index = listBox1.FindString(myString, -1);//username 

    if (index != -1) 
    { 
     listBox1.SetSelected(index, true);//username 
     MessageBox.Show("ok"); 
    } 
    else 
    { 
     listBox1.SetSelected(index, false);//username 
     MessageBox.Show("error"); 
    } 

} 
+2

什麼錯誤....? – Gusman

+3

爲什麼你試圖訪問索引時,它被設置爲-1在其他部分'listBox1.SetSelected(index,false);' –

回答

1

您試圖設置一個項目在您的列表框中被選中,但是您傳入的索引是-1。如果在列表框中找不到該字符串,則不能將任何項目設置爲false。你可以做一些其他的事情,比如循環遍歷所有可用的項目並將它們設置爲false,但這取決於你想要在那個找不到你想要的字符串的情況下發生的事情。你可能只想在TBH的其他條款中不做任何事情。

if (index != -1) 
{ 
    listBox1.SetSelected(index, true);//username 
    MessageBox.Show("ok"); 
} 
else 
{ 
    listBox1.SetSelected(index, false);//username // Index == -1 here. This will FAIL. 
    MessageBox.Show("error"); 
}