搜索功能不会显示

时间:2019-11-19 02:57:38

标签: c# sql search datagridview

我正在尝试使用显示在datagridview中的文本框实现搜索功能。我希望它是这样,无论我试图从项目名称还是位置搜索哪个列,它都将显示在datagridview中。但是,当我在文本框中键入内容时,datagridview不会更改。谢谢你这是代码:

string sql = "SELECT * FROM Project "+"WHERE(ProjectName LIKE @Search)"+ " OR(NumberOfUnits LIKE @Search)"+ "OR(Location LIKE @Search)";
using (var con = new SqlConnection(@"Data Source=HAZWAN-PC\SQLEXPRESS;Initial Catalog=wantest2;Integrated Security=True"))
{
    using (var cmd = new SqlCommand(sql, con))
    {
        cmd.Parameters.AddWithValue("@Search", "%" + txtSearch.Text + "%");
        con.Open();
        try
        {
            cmd.ExecuteNonQuery();
        }
        catch (SqlException er)
        {
            MessageBox.Show("There was an error accessing your data. DETAIL: " + er.ToString());
        }

        dataGridView1.DataSource = null;
        BindGrid();
    }
}

1 个答案:

答案 0 :(得分:0)

绑定GridView时缺少某些元素或代码行。

您必须使用SqlDataAdapter从数据库中提取数据并将其存储到DataSetDataTable中,以进行与gridview绑定的进一步处理。

尝试以下代码:

            DataTable dt = new DataTable();
            SqlDataAdapter da;
            string sql = "SELECT * FROM Project WHERE ProjectName LIKE @Search OR NumberOfUnits LIKE @Search OR Location LIKE @Search";
            using (var con = new SqlConnection(@"Data Source=HAZWAN-PC\SQLEXPRESS;Initial Catalog=wantest2;Integrated Security=True"))
            {
                using (var cmd = new SqlCommand(sql, con))
                {
                    cmd.Parameters.AddWithValue("@Search", "%" + txtSearch.Text + "%");

                    try
                    {
                        con.Open();
                        //cmd.ExecuteNonQuery(); 
                        //Instead of above method you have to use 
                        da = new SqlDataAdapter(cmd);
                        da.Fill(dt);
                        da.Dispose();
                        dataGridView1.DataSource = dt;
                        con.Close();
                    }
                    catch (SqlException er)
                    {
                        con.Close();
                        dataGridView1.DataSource = null;
                        MessageBox.Show("There was an error accessing your data. DETAIL: " + er.ToString());
                    }             

                }
            }

您可以将以上代码包装在RefreshGridBindGrid等单一方法中,并根据需要调用该方法。