user1779026
user1779026

Reputation: 93

Simple search programme does not return results c#

I am trying to do a simple search program that allows the user to search for an employee's name and click on the search button which will return the employee details.

In my Form I have:

    private void buttonSearch_Click(object sender, EventArgs e)
    {
        //set datasource
        dataGridView1.DataSource = controller_emp.search_employee(textBoxSearch.Text);
    }

Controller_Employee:

    public Model_Employee search_employee(string criteria)
    {
        return db.search_employee(criteria);
    }

Model_DB_Employee:

    public Model_Employee search_employee(string criteria)
    {

        Model_Employee result = new Model_Employee();
        for (int i = 0; i < rows.Count; i++)
        {
            if ((string)empTab.Rows[i]["emp_fname"] == criteria)
            {
                result.setId(empTab.Rows[i]["emp_id"].ToString());
                result.setFname(empTab.Rows[i]["emp_fname"].ToString());
                result.setLname(empTab.Rows[i]["emp_lname"].ToString());
                result.setUsername(empTab.Rows[i]["username"].ToString());
                result.setPassword(empTab.Rows[i]["passwd"].ToString());
                result.setJobrole(empTab.Rows[i]["job_role"].ToString());
                result.setContact(empTab.Rows[i]["contact"].ToString());
                result.setEmail(empTab.Rows[i]["email"].ToString());
            }

        }
        return result;

    }

Is there anything wrong with the for loop? It keeps on looping even when the criteria has been met.

Upvotes: 0

Views: 133

Answers (2)

Axis
Axis

Reputation: 846

Use break;

for (int i = 0; i < rows.Count; i++)
{
    if ((string)empTab.Rows[i]["emp_fname"] == criteria)
    {
        //result stuff
        break;
    }
}
return result;

Upvotes: 1

GeorgeVremescu
GeorgeVremescu

Reputation: 1253

You did not exit the loop when you found the employee. You can: 1. Use break immediately after populating the result with the information 2. copy the return result; immediately after populating the result with the information

I like best option number 1 :)

Upvotes: 0

Related Questions