Carl_Honcho
Carl_Honcho

Reputation: 73

Search string in Listbox

I'm having troubles finding a string into a listbox, my string NombreCompleto is made of 3 strings that I previously had read from a file(ESSD), after I had recovered this string, I want to know if this string is in my listbox3, I tried several methods but it doesnt seem to work. Here is my code.

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 :@"); }
}

Upvotes: 0

Views: 1152

Answers (3)

Andrija Pavlovic
Andrija Pavlovic

Reputation: 107

Really easy way to find if a certain string is in a listbox.

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();
}

Upvotes: 0

user586399
user586399

Reputation:

Try this out:

                            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 :@");

Upvotes: 0

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can try with this code - based on Linq operator Where, ...

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

if(selectedItems.Any()) 
.... 

Upvotes: 1

Related Questions