asp.net根据textbox1(id字段)和textbox2(name字段)内容查询数据库,如果为空表示没有限制,怎么实现的?

来源:百度知道 编辑:UC知道 时间:2024/06/13 22:37:08
用IF语句根据是否为空来修改SQL语句,如果textbox多了,好象会很复杂,比如server126的答案里那个else语句里的where条件好象也要分textbox1或textbox2为空来写

拼接
string condtion ="1=1 ";
if(textbox1.Text!="")
condtion=condtion+"and id=" + textbox1.Text + " ";
if(textbox2.Text!="")
condtion=condtion+" and name='" + textbox2.Text + "' ";
if(condtion!="")
sqlstring ="slect .... where "+ condtion;

string sql = "select * from tablename where 1=1 ";
if(textbox1.Text != "")
{
sql+=" and id = '"+textbox1.Text+"'";
}
if(textbox2.Text != "")
{
sql +=" and name = '"+textbox2.Text+"'";
}

可以这样:
string id=textbox1.Text.Trim();
string name=textbox2.Text.Trim();
if(id=="")
{
id="%";
}
if(name=="")
{
name="%";
}
string sql="select * from 表1 where id like '"+id+"