我正在尝试在我的代码中构建一个查询并将其连接到数据源以重新加载数据。不幸的是,只有当Author包含在where子句中时,查询才有效。否则我没有得到任何结果。
例如:
单独搜索作者(国王),返回准确的结果。
SELECT
[Title], [Author], [Category], [Image], [Binding], [Price],
[ProductID], [Average Rating] AS Average_Rating
FROM [tblProducts]
WHERE (Author LIKE ‘%king%')
搜索作者(国王)和标题(dif),返回准确的结果。
SELECT
[Title], [Author], [Category], [Image], [Binding], [Price],
[ProductID], [Average Rating] AS Average_Rating
FROM [tblProducts]
WHERE (Author LIKE '%king%') AND (Title LIKE ‘%dif%’)
单独搜索标题(dif),未返回任何结果。
SELECT
[Title], [Author], [Category], [Image], [Binding], [Price],
[ProductID], [Average Rating] AS Average_Rating
FROM [tblProducts]
WHERE (Title LIKE ‘%dif%')
如果所有用户输入的值都为空,则不会返回任何结果。
SELECT
[Title], [Author], [Category], [Image], [Binding], [Price],
[ProductID], [Average Rating] AS Average_Rating
FROM [tblProducts]
我确信这是一件我想念的简单事,但我无法理解。任何帮助表示赞赏。
以下是我的相关代码:
if (Page.IsValid)
{
System.Web.UI.WebControls.AccessDataSource tmpAccessConnection = new System.Web.UI.WebControls.AccessDataSource();
//Set file location
//Connection strings are not used with unprotected Access databases
tmpAccessConnection.DataFile = "~/App_Data/propdbA2003.mdb";
tmpAccessConnection.ID = "adsPropertyListing";
tmpAccessConnection.DataSourceMode = SqlDataSourceMode.DataSet;
//build query
tmpAccessConnection.SelectCommand = "SELECT [Title], [Author], [Category], " +
"[Image], [Binding], [Price], [ProductID], [Average Rating] AS Average_Rating " +
" FROM [tblProducts]";
String stmntWhere = "";
if (!textAuthor.Text.Equals(""))
{
stmntWhere += "(Author LIKE '%" + textAuthor.Text + "%')";
}
if (!textBookTitle.Text.Equals(""))
{
if(!stmntWhere.Equals(""))
stmntWhere += " AND "; //add AND if the stmnt has other parameters
stmntWhere += "(Title LIKE '%" + textBookTitle.Text + "%')";
}
if (!textISBN.Text.Equals(""))
{
if (!stmntWhere.Equals(""))
stmntWhere += " AND "; //add AND if the stmnt has other parameters
stmntWhere += "((ISBN LIKE '%" + textISBN.Text + "%')" +
" OR (ISBN13 LIKE '%" + textISBN.Text + "%'))";
}
if (checkInclude.Checked)
{
if (!stmntWhere.Equals(""))
stmntWhere += " AND "; //add AND if the stmnt has other parameters
stmntWhere += "(Category = " + dropDwnCategory.SelectedValue + ")";
}
if (!stmntWhere.Equals(""))
tmpAccessConnection.SelectCommand += " WHERE " + stmntWhere;
adsSearch.SelectCommand = tmpAccessConnection.SelectCommand;
anAccessDataSource.SelectCommand = tmpAccessConnection.SelectCommand;
gridViewBrowseAll.DataSourceID = "adsSearch";
//reset page to 1st page if new search is initiated from revised query
gridViewBrowseAll.PageIndex = 0;
//Set AutoGenerateColumns property to true in code or web form
try
{
gridViewBrowseAll.DataBind();
}
catch (Exception ex)
{
Response.Write("Binding exception in btnPropNoSearch_Click<BR>");
Response.Write("Access Exception Handler: {0} " + ex.ToString());
}
}