查询条件问题
前台界面上有N个选择项和text提供查询条件,后台获取各控值,为空的不做为条件 ,不为空的全部累加,做为where的查询条件,要如何实现?
如:
if (WNo.Text != "")
{
sqlstr = sqlstr + "Wk=='" + WNo.Text + "' and";
}
查询结果要直接绑定到GridView1上。请教高手指点,谢谢! 查询条件 GridView where
[解决办法]
本帖最后由 q107770540 于 2013-08-22 19:43:08 编辑
public string Test(string a, string b, string c,string d)
{
string sql = "SELECT * FROM Users WHERE 1=1";
if (!string.IsNullOrEmpty(a))
{
sql += " AND name='" + a + "'";
}
if (!string.IsNullOrEmpty(b))
{
sql += " AND age='" + b+ "'";
}
if (!string.IsNullOrEmpty(c))
{
sql += " AND sex='" + c + "'";
}
if (!string.IsNullOrEmpty(d))
{
sql += " AND address='" + d + "'";
}
return sql.ToString();
}
现在我们使用linq来实现上边的代码:
public void Test(string a, string b, string c,string d)
{
QueryContext query = new QueryContext();
var q = from u in query.Users
select u;
if (!string.IsNullOrEmpty(a))
{
q = q.Where(p => p.name == a);
}
if (!string.IsNullOrEmpty(b))
{
q = q.Where(p => p.age == b);
}
if (!string.IsNullOrEmpty(c))
{
q = q.Where(p => p.sex == c);
}
if (!string.IsNullOrEmpty(d))
{
q = q.Where(p => p.address == d);
}
q.ToList();
}
QueryContext query = new QueryContext();
var q = from u in query.Users
select u;
if (!string.IsNullOrEmpty(a))
{
q = q.Where(p => p.name == a);
}
if (!string.IsNullOrEmpty(b))
{
q = q.Where(p => p.age == b);
}
if (!string.IsNullOrEmpty(c))
{
q = q.Where(p => p.sex == c);
}
if (!string.IsNullOrEmpty(d))
{
q = q.Where(p => p.address == d);
}
GridView1.DataSource = q.ToList();
GridView1.DataBind();