在不输入任何数据的情况下,点击查询后可以搜索出所有的记录,若输入任何一个条件,则只查询出符合条件的记录,代码如下:
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 }
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 }