实现查询多个条件的功能,就是拼接字符串
protected void btnSearch_Click(object sender, EventArgs e) //直接连接数据库查询
{
string sql = "select * from Student s where 1=1";
if (!string.IsNullOrEmpty(txtName.Text))
sql += "and s.s_name='" + txtName.Text.Trim() + "'";
if (!string.IsNullOrEmpty(txtSex.Text))
sql += "and s.s_sex='" + txtSex.Text.Trim() + "'";
if (!string.IsNullOrEmpty(txtDep.Text))
sql += "and s.d_num='" + txtDep.Text.Trim() + "'";
if (!string.IsNullOrEmpty(txtClass.Text))
sql += "and s.c_num='" + txtClass.Text.Trim() + "'";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "Child");
GridView1.DataSource = ds.Tables["Child"];
GridView1.DataBind();
}
protected void btnSearchL_Click(object sender, EventArgs e) //LINQ查询
{
StudentCont.StudentDataContext stu = new StudentCont.StudentDataContext();
var q = from s in stu.Student select s;
if (!string.IsNullOrEmpty(txtName.Text))
q=q.Where(t => t.s_name == txtName.Text.Trim());
if (!string.IsNullOrEmpty(txtSex.Text))
q=q.Where(t => t.s_sex == txtSex.Text.Trim());
if (!string.IsNullOrEmpty(txtDep.Text))
q=q.Where(t => t.d_num == txtDep.Text.Trim());
if (!string.IsNullOrEmpty(txtClass.Text))
q=q.Where(t => t.c_num == txtClass.Text.Trim());
GridView2.DataSource = q;
GridView2.DataBind();
}
以上代码是参考别人的写出来的,也贴出来给大家参考。
原创:http://blog.csdn.net/q107770540/article/details/5724013#comments