2012-09-18 55 views
0

我遇到麻煩,找到一個字符串到一個列表框中,我的字符串NombreCompleto由我以前從文件(ESSD)中讀取的3個字符串組成,在恢復了該字符串後,我想知道如果這個字符串在我的listbox3中,我嘗試了幾種方法,但它似乎不起作用。 這是我的代碼。在Listbox中搜索字符串

foreach (string h in Directory.EnumerateFiles(NomDirec, "resume*")) 
{ 
    this.listBox1.Items.Add(h); 
    var NombreLinea = File.ReadLines(h); 
    foreach (string item in NombreLinea) 
    { 
     NombreAbuscar.Add(item.Remove(item.IndexOf(':'))); 
     this.listBox3.Items.Add(item.Remove(item.IndexOf(':'))); 

} 

foreach (string t in Directory.EnumerateFiles(NomDirec, "ESSD1*")) 
{ 
    string[] Nombre = File.ReadLines(t).ElementAtOrDefault(6).Split(':'); 
    string[] ApellidoPat = File.ReadLines(t).ElementAtOrDefault(7).Split(':'); 
    string[] ApellidoMat = File.ReadLines(t).ElementAtOrDefault(8).Split(':'); 
    string NombreCompleto = ApellidoPat[1]+" "+ ApellidoMat[1] +","+" "+ Nombre[1]; 
    string Nom2 = NombreCompleto.ToString(); 

    int index = listBox3.FindString(Nom2); 
    if (index != -1) 
    { 
     this.listBox1.Items.Add(t); 
     MessageBox.Show("Find It"); 
    } 
    else { MessageBox.Show("Not Found :@"); } 
} 

回答

0

嘗試了這一點:

      int index = -1; 
          for (int i = 0; i < listBox3.Items.Count; ++i) 
           if (listBox3.Items[i].Text == Nom2) { index = i; break; } 
          if (index != -1) 
          { 
           this.listBox1.Items.Add(t); 
           MessageBox.Show("Find It"); 
          } 
          else { MessageBox.Show("Not Found :@"); 
+0

什麼是ind?你在哪裏申報?謝謝! –

+0

@carloscarbajal對不起。我只是想'索引' – 2012-09-19 14:50:57

1

您可以使用此代碼嘗試 - based on Linq operator Where, ...

var selectedItems = from li in listBox3.Items 
        where li.Text == Nom2 
        select li.Text; 

if(selectedItems.Any()) 
.... 
+3

您可以使用'Any'而不是'Count()== 0)'。它不僅傳達了更清晰的意思,而且表現也會更好(不需要遍歷整個序列,只需要獲得第一個項目)。您還需要刪除'ToList',因爲不需要急切地將整個序列迭代到列表中。 – Servy

+0

謝謝Servy非常好的評語 –

+0

對於LINQ Simplicity :) +1 –

0

非常簡單的方法找到,如果某個字符串在列表框中。

private void btnAddRecipe_Click(object sender, EventArgs e) 
{ 
    bool DoesItemExist = false; 
    string searchString = txtRecipeName.Text; 
    int index = lstRecipes.FindStringExact(searchString, -1); 

    if (index != -1) DoesItemExist = true; 
    else DoesItemExist = false; 

    if (DoesItemExist) 
    { 
     //do something 
    } 
    else 
    { 
     MessageBox.Show("Not found", "Message", MessageBoxButtons.RetryCancel, MessageBoxIcon.Stop); 
    } 

    PopulateRecipe(); 
}