該代碼能夠根據搜索表單文本框中提供的值搜索數據並將其加載到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注入攻擊。 – nvoigt
爲什麼在查詢字符串之外的行AND ANDDeleted ='0''? – LightBulb