string sql = "select * from customer where name like '" + textBox2.Text + "%'";
string sql2 = "select * from customer";
if (textBox2.Text.Length > 0)
{
DataTable dt = CarDatabase.executeSelect(sql);
DataTable dt2 = CarDatabase.executeSelect(sql2);
if (dt == null)
{
dataGridView2.DataSource = dt2;
MessageBox.Show("There's no result with " + textBox2.Text);
}
else if (dt != null)
dataGridView2.DataSource = dt;
}
else
{
MessageBox.Show("Please fill the textbox");
}
我尝试“如果like
有一些结果,请在DataGrid
”中显示。没问题。但是,当like
在数据库中找不到任何内容时,DataGrid
会保持旧状态。但是,如果在搜索后没有结果,则DataGrid
为空。
答案 0 :(得分:1)
string sql = "select * from customer where name like '" + textBox2.Text + "%'";
string sql2 = "select * from customer";
if (textBox2.Text.Length > 0)
{
DataTable dt = CarDatabase.executeSelect(sql);
DataTable dt2 = CarDatabase.executeSelect(sql2);
if (dt == null)
{
dataGridView2.DataSource = dt2;
dataGridView2.DataBind();
MessageBox.Show("There's no result with " + textBox2.Text);
}
else if (dt != null)
{
dataGridView2.DataSource = dt;
dataGridView2.DataBind();
}
}
else
{
MessageBox.Show("Please fill the textbox");
}
答案 1 :(得分:1)
使用存储过程比从代码中注入sql查询更好。
我会创建一个像这样的程序......
Create Procedure GetCustomers(@name varchar(100))
AS
BEGIN
select * from customer where Name like (ISNULL(@name,Name))
END
但是,在将值传递给@name参数时,您需要向其追加'%'。如果textbox值为空,则将null传递给@name。如果文本框值为空,则此查询将返回所有客户,否则将返回所请求的客户。
答案 2 :(得分:0)
您必须使用DataBind()
在if else块中执行以下行
dataGridView2.DataBind();
更新:
if (dt == null)
{
DataTable table = new DataTable();
dataGridView2.DataSource = table ;
MessageBox.Show("There's no result with " + textBox2.Text);
}