【发布时间】:2017-05-19 14:46:31
【问题描述】:
此代码能够根据搜索表单文本框中提供的值搜索并将数据加载到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"];
}
【问题讨论】:
-
请使用绑定参数,您的代码容易受到 SQL 注入攻击。
-
为什么
AND IsDeleted = '0'行在您的查询字符串之外?
标签: c# sql-server search