我的动态查询
昨天在做毕业设计的过程中有一个动态查询的功能让我困惑了很长时间,主要还是sql不知道怎么拼,最后想到了一种感觉不是很好的办法,但是解决了我的问题,今天帖出来,想让各位看看,你们在工作中是怎么解决类似问题的,谢谢!
![]()
在不输入任何数据的情况下,点击查询后可以搜索出所有的记录,若输入任何一个条件,则只查询出符合条件的记录,代码如下:

在不输入任何数据的情况下,点击查询后可以搜索出所有的记录,若输入任何一个条件,则只查询出符合条件的记录,代码如下:
1
protected void Button1_Click(object sender, EventArgs e)
2
{
3
string name = "";
4
string sex = "";
5
string address = "";
6
if (txtaddress.Text.Length > 0)
7
{
8
address = " gaddress like '" + "%"+"'+'"+txtaddress.Text+"'+'"+"%'";
9
}
10
else
11
{
12
address = " 1=1 ";
13
}
14
if (txtname.Text.Length > 0)
15
{
16
name = "gname = '" + txtname.Text + "'";
17
}
18
else
19
{
20
name = " 1=1 ";
21
}
22
if (ddlsex.SelectedIndex != 0)
23
{
24
sex = " gsex = '" + ddlsex.SelectedValue.ToString() + "'";
25
}
26
else
27
{
28
sex = " 1=1";
29
}
30
string where = name + " and "+sex+" and "+address;
31
string sql = "select * from guest where " + where;
32
SqlConnection conn = new SqlConnection("server=.;uid=sa;database=Test");
33
SqlDataAdapter dap = new SqlDataAdapter(sql, conn);
34
DataTable dt = new DataTable();
35
dap.Fill(dt);
36
GridView1.DataSource = dt;
37
GridView1.DataBind();
38
}
protected void Button1_Click(object sender, EventArgs e)2
{3
string name = "";4
string sex = "";5
string address = "";6
if (txtaddress.Text.Length > 0)7
{8
address = " gaddress like '" + "%"+"'+'"+txtaddress.Text+"'+'"+"%'";9
}10
else11
{12
address = " 1=1 ";13
}14
if (txtname.Text.Length > 0)15
{16
name = "gname = '" + txtname.Text + "'";17
}18
else19
{20
name = " 1=1 ";21
}22
if (ddlsex.SelectedIndex != 0)23
{24
sex = " gsex = '" + ddlsex.SelectedValue.ToString() + "'";25
}26
else27
{28
sex = " 1=1";29
}30
string where = name + " and "+sex+" and "+address;31
string sql = "select * from guest where " + where;32
SqlConnection conn = new SqlConnection("server=.;uid=sa;database=Test");33
SqlDataAdapter dap = new SqlDataAdapter(sql, conn);34
DataTable dt = new DataTable();35
dap.Fill(dt);36
GridView1.DataSource = dt;37
GridView1.DataBind();38
}

浙公网安备 33010602011771号