繁体   English   中英

else数据表的声明

[英]else statement of Datatable

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为空。

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");
}

那么使用存储过程比从代码中注入sql查询更好。

我会创建一个像这样的程序......

Create Procedure GetCustomers(@name varchar(100))
AS 
BEGIN
 select * from customer  where Name like (ISNULL(@name,Name))
END

但是,在将值传递给@name参数时,您需要将'%'附加到它。 如果textbox值为空,则将null传递给@name。 如果文本框值为空,则此查询将返回所有客户,否则返回所请求的客户。

您必须使用DataBind()

在if else块中执行以下行

dataGridView2.DataBind();

更新:

           if (dt == null)
            {
                DataTable table = new DataTable();
                dataGridView2.DataSource = table ;
                MessageBox.Show("There's no result with " + textBox2.Text);
            }

暂无
暂无

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

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