如何使用ASP.Net从数据库中搜索多个文本框?
protected void SearchButton_Click(object sender, EventArgs e)
{if (RefNo.Text == "@search")
{
string str = "Select [ITEM No#], [Company Name], [Discipline Required], [Service Description], Institution, [Award Date] from PSP_Report where ([ITEM NO#] like '%' + @search + '%')";
SqlCommand xp = new SqlCommand(str, con);
xp.Parameters.Add("@search", SqlDbType.NVarChar).Value = RefNo.Text;
con.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "ITEM No#");
Search.DataSource = ds;
Search.DataBind();
con.Close();
}
else if (CompanyName.Text == "@searche")
{
string str = "Select [ITEM No#], [Company Name], [Discipline Required], [Service Description], Institution, [Award Date] from PSP_Report where ([Company Name] like '%' + @searche + '%')";
SqlCommand xp = new SqlCommand(str, con);
xp.Parameters.Add("@search", SqlDbType.NVarChar).Value = RefNo.Text;
con.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Company Name");
Search.DataSource = ds;
Search.DataBind();
con.Close();
}
}
}
答案 0 :(得分:0)
根据我的理解,我假设您的搜索GUI上有多个文本框,并且您希望根据用户输入动态构建一个select语句。
一种方法就是如下。在确定select是你想要的之后,然后有一个方法用你构造的select执行你的查询。
protected void SearchButton_Click(object sender, EventArgs e)
{
string str = "Select [ITEM No#], [Company Name], [Discipline Required], [Service Description], Institution, [Award Date] from PSP_Report where 1=1 ";
if (!string.IsNullOrWhiteSpace(RefNo.Text))
{
str += $" and ([ITEM NO#] like '%'{RefNo.Text}'%')";
}
if (!string.IsNullOrWhiteSpace(CompanyName.Text))
{
str += $" and ([Company Name] like '%'{CompanyName.Text}'%')";
}
PS:
请注意SQL注入。
我不会在列名上使用#或空格。