简体   繁体   中英

Unable To Fetch Records From SQL Table To DataGridView In C#

I have a windows form where the user can input multiple values in multiple textboxes for faster search results. But when running, it takes only 1st parameter ie, the fullname and ignores the other. Don't know the reason why is it so. Am getting the full table in the result which I don't want.

private void btnSubmit_Click(object sender, EventArgs e)
{   
    SqlConnection con = new SqlConnection("Data Source=MADDY-PC\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True");

    try
    {
        con.Open();

        string sql = "SELECT * FROM Customers WHERE ContactName LIKE '%" + txtFullName.Text + "%' OR Address LIKE '%" + txtAddress.Text + " %' OR Phone LIKE '%"+txtContactNumber.Text+"%'";

         SqlCommand cmd = new SqlCommand(sql, con);

         SqlDataAdapter da = new SqlDataAdapter(cmd);
         DataTable ds = new DataTable();
         da.Fill(ds);
         if (ds.Rows.Count > 0)
         {
             dataGridView1.DataSource = ds;
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message.ToString());
     }
     finally
     {
         con.Close();
     }
 }

Where am I making mistake, please guide me.

Thanks

I think when a user leaves a textbox empty, she doesn't want the condition the textbox entry corresponds to, be included and that's where it seems the current one going wrong. But this is an assumption and needs to verified by you.

So in my opinion the query should be built like this:

string sql = "SELECT * FROM Customers "
string condition = String.Empty;

if(!String.IsNullOrEmpty(txtFullName.Text))
  condition  += "WHERE ContactName LIKE '%" + txtFullName.Text + "%' "

if(!String.IsNullOrEmpty(txtAddress.Text))
  if(!String.IsNullOrEmpty(condition))
     condition  += "OR Address LIKE '%" + txtAddress.Text + " %' "
  else
     condition  += "WHERE Address LIKE '%" + txtAddress.Text + " %' " 

//and so on....


sql = sql + condition;
SqlCommand cmd = new SqlCommand(sql, con);

Also, I hope you won't forget to add a dataGridView1.Databind() statement. Let me know if this observation was correct.

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