简体   繁体   English

无法在C#中将记录从SQL表提取到DataGridView

[英]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. 我有一个Windows窗体,用户可以在其中在多个文本框中输入多个值以获得更快的搜索结果。 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. 另外,希望您不要忘记添加dataGridView1.Databind()语句。 Let me know if this observation was correct. 让我知道这种观察是否正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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