此代码能够根据搜索表单文本框中提供的值搜索数据并将数据加载到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"];
}
答案 0 :(得分:3)
String.IsNullOrEmpty
检查值是null还是空。AND
,如果您添加,则在第二个条件(tbxRevision
)的开头,如果tbxDocumentNo
则查询变为错误是null或空。类似于上一个情况,如果最后一个条件为假,那么查询将以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);
}
}
答案 1 :(得分:1)
如果您不希望SQL命令包含子句AND Revision Like ''
,则需要停止将SQL命令硬编码为单个字符串,而是根据输入框构建该字符串。
StringBuilder sqlCommandText = new StringBuilder();
sqlCommandText.Append("Select DocumentNo , Revision, DocumentTitle, DocumentType FROM DocumentLog WHERE IsDeleted = 0");
if(!string.IsNullOrEmpty(tbxRevision.Text))
{
sqlCommandText.Append(" AND Revision Like @revision");
command.Parameters.Add("@revision", tbxRevision.Text);
}
// do this for all fields
command.CommandText = sqlCommandText.ToString();
答案 2 :(得分:0)
您好可以使用一些查询逻辑,例如查询可以是:
NaT