此代码能够根据搜索表单文本框中提供的值搜索数据并将其加载到 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/