Find data in data set

I’ve googled this found a few useful sites that have helped me out but not sure exactly what is going wrong. I have my database with data in it. I can display data on the page load and I can sort through the data with next and previous buttons, but the issue is my find button is not working and always display my “no rows found” message when searching for a name. I’m sure there is a more efficient way to do this but havent looked in to that just yet.

Thanks

Here is my code:

string searchFor = txtSearch.Text.Trim();
    int results = 0;

    OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:AddressBook.mdb");

    conn.Open();
    DataSet ds = new DataSet();
    string cmd = "SELECT * FROM tblAddressBook";

    OleDbDataAdapter da = new OleDbDataAdapter(cmd, conn);
    da.Fill(ds, "Info");

    DataRow[] returedRows;
    DataRow dr;
    returedRows = ds.Tables.Select("LastName=' " + searchFor + " ' ");
    results = returedRows.Length;

    if (results > 0)
    {   
        dr = returedRows[0];
        txtFirstName.Text = dr["FirstName"].ToString();
        txtLastName.Text = dr["LastName"].ToString();
        txtEmail.Text = dr["Email"].ToString();
        txtPhone.Text = dr["PhoneNumber"].ToString();
    }
    else
    {
        lblReturned.Text = "No Rows Found";
    }

    //close the connection
    conn.Close();

Answer

Your .Select string is adding a space to the beginning and end of the search term. If searchFor contained Thompson then your statement would be

.Select("LastName=' Thompson ' ")

so no entries would match unless they had a leading space. Also, I had no idea what ds.tblAddressBook had to do with anything so I just used this instead:

returedRows = ds.Tables["Info"].Select("LastName='" + searchFor + "'");

Now you need to tweak your code so it won’t blow up when somebody tries to search for O'Connor.

Leave a Reply

Your email address will not be published. Required fields are marked *