c# - 在数据库中搜索时忽略空文本框

标签 c# sql-server search

此代码能够根据搜索表单文本框中提供的值搜索数据并将其加载到 DataGridView。如果我将任何文本框留空,则不会有搜索结果,因为 SQL 查询是用“AND”组合的。

如何在搜索时忽略空文本框(通过 SQL 查询或 C# 代码)?

private void btnSearch_Click(object sender, EventArgs e)
{
    DataSet ds = new DataSet();

    String select = "SELECT DocumentNo, Revision, DocumentTitle, DocumentType
                     FROM DocumentLog
                     WHERE DocumentNo Like '%" + tbxDocumentNo.Text + "%'
                       AND Revision Like '%" + tbxRevision.Text + "%'
                       AND DocumentTitle Like '%" + tbxDocumentTitle.Text + "%'
                       AND DocumentType '%" + tbxDocumentType.Text + "%'"
                       AND IsDeleted = '0';

    SqlConnection conn = DBConnection.openConnection();
    SqlCommand command = new SqlCommand(select, conn);

    SqlDataAdapter da = new SqlDataAdapter(command);
    da.Fill(ds, "DocumentLog");

    dgvTracking.AutoGenerateColumns = false;
    dgvTracking.DataSource = ds.Tables["DocumentLog"];
}

最佳答案

  • 首先,您必须将连接的字符串查询替换为参数化查询以避免注入(inject),
  • 其次,您可以使用 String.IsNullOrEmpty 来检查值是否为 null 或空,然后再将它们添加到 where 子句。
  • 您需要注意的第三件事是多个条件分隔符,即 AND,如果您在第二个条件 (tbxRevision) 的开头添加 then,则查询将变为如果 tbxDocumentNo 为 null 或为空,则会出现错误。与last的情况类似,如果最后一个条件为假,那么查询将以AND结束,这也是一个错误,为了避免这些,我们可以采取IsDeleted='0' > 作为第一个条件,就像我在下面的代码中所做的那样,

请看一下:

string querySQL = "Select DocumentNo , Revision, DocumentTitle, DocumentType FROM DocumentLog WHERE IsDeleted='0'";
using(SqlConnection conSQL = DBConnection.openConnection())
{
    using(SqlCommand cmdSQL = new SqlCommand())
    {
        if(!string.IsNullOrEmpty(tbxDocumentNo.Text))
        {
            querySQL += "AND  DocumentNo Like @DocumentNo";
            cmdSQL.Parameters.Add("@DocumentNo", SqlDbType.VarChar).Value = "%" + tbxDocumentNo.Text + "%";
        }

        // Add rest of conditions here like this

        cmdSQL.CommandText=querySQL;
        cmdSQL.Connection = conSQL;
    SqlDataAdapter da = new SqlDataAdapter(cmdSQL);                                     
    }
}

关于c# - 在数据库中搜索时忽略空文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41478585/

相关文章:

c# - 我的 MVVM 模式不起作用……为什么?

c# - 在 C# 中使用方法将华氏度转换为摄氏度

sql-server - 如何在 Kubernetes Pod 中执行 sql 脚本文件?

php - 如何在mysql中使用普通列对聚合函数进行搜索

sql - sql server 比较同一个数据库中的两个表的数据

android - google-play-store 可见性算法或想法有问题

c# - Rapidshare 高级下载 (c#)

c# - x :Bind syntax for event binding giving error CS0122: inaccessible due to protection level

java - 如何连接 DisMax 处理程序 solr?

c++ - Qt5 中字符串搜索的最佳容器