简体   繁体   中英

c# Finding a string from a list that contains the text box text

I'm trying to search for a string in a list that contains the text box's text. Then when it finds the record, adds it to a flow layout panel. It doesn't seem to be working properly.

I have 3 employees:

  • Richard Jacobs
  • Olivia Mularczyk
  • Jess Mularczyk

All employees are added to the EmployeeList.

GUI

When I type 'R' into the text box, only Richard shows up which is good! But when I type in 'Ri' it doesn't show up. Also When I type in 'O' or 'Olivia' that employee doesn't show up either!

Code:

if (EmployeeTb.Text != string.Empty)
{
    ResultsFLP.Controls.Clear();

    foreach (Cerealto.Classes.Employee Employee in Cerealto.Classes.Employees.EmployeeList)
    {
        if (Employee.firstName.Contains(EmployeeTb.Text))
        {
            ESR = new EmployeeSearchResultUC(Employee.employeeID, Employee.firstName + " " + Employee.lastName);
            ResultsFLP.Controls.Add(ESR);
        }
    }
}
else
{
    ResultsFLP.Controls.Clear();

    foreach (Cerealto.Classes.Employee Employee in Cerealto.Classes.Employees.EmployeeList)
    {
        ESR = new EmployeeSearchResultUC(Employee.employeeID, Employee.firstName + " " + Employee.lastName);
        ResultsFLP.Controls.Add(ESR);
    }
}

I hope you guys can help! :D

If i understood your intentions properly,

a. you can use Lambda expression its not a bad practice to learn this days.
b. notice my comment about your logic.
c. also use ToLower() if you want to search without considering if the user enters small letter or capital letter (can produce the problem you are presenting in that question) "Ri" is not "rI" and "RI" is not "ri" etc..

if (EmployeeTb.Text != string.Empty)
{
    ResultsFLP.Controls.Clear(); 
    var emp = Cerealto.Classes.Employees.EmployeeList.AsEnumerable().Where(x=> (x.firstName+ " " + x.lastName).ToLower().Contains(EmployeeTb.Text.ToString().ToLower().Trim())).Select(e=>e).ToList();

    if(emp != null)
    {
        foreach(Cerealto.Classes.Employee Employee e in emp)
        {
             ESR = new EmployeeSearchResultUC(e.employeeID, e.firstName + " " + e.lastName);
             ResultsFLP.Controls.Add(ESR);
        }
    }
}
else
{
    // there is no results here clear everything or make no change (dont use the line ResultsFLP.Controls.Clear(); / load all employees again)
    ResultsFLP.Controls.Clear();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM