C#.NET 模糊组合查询的例子

string WhereText =" where";
            
if (Sender !=""|| Receive !=""|| DeleteTime !="")   
      {
                
if (Sender.text.length>0)
      
{
                     WhereText
+=" SenderName like '%"+ Sender +"%' and";  
      }
               if (Receive.text.length>0)
      {
                    WhereText
+=" AddresseeName like   '%"+ Receive +"%' and";
      }
               
if (DeleteTime.text.length>0)
      {
                     WhereText
+=" convert(varchar(10),DeleteTime,120) ='"+ DeleteTime +"' and";
                 }
             }


            
else
      
{
                 WhereText
="";
      }

     
string cmdText ="select * from [SMS_DELETED]";
            
if (WhereText !="")
      {
                 cmdText
+= WhereText.Substring(0, WhereText.Length -4);//去掉最后一个and
      }

===============================================

代码
1 //查询
2  protectedvoid btn_cx_Click(object sender, EventArgs e)
3 {
4 string WhereText =" where";
5 string cmdText ="select * from htjbxxb";
6 if (txt_htbh.Text.Length >0)
7 {
8 WhereText +=" htbh='"+ txt_htbh.Text.Trim() +"' and";
9 }
10 if (txt_htmc.Text.Length >0)
11 {
12 WhereText +=" htmc like '%"+ txt_htmc.Text.Trim() +"%' and";
13 }
14 if (txt_wgrq.Text.Length >0)
15 {
16 WhereText +=" wgrq= '"+ txt_wgrq.Text.Trim() +"' and";
17 }
18 if (txt_jfdw.Text.Length >0)
19 {
20 WhereText +=" jfdw like '%"+ txt_jfdw.Text.Trim() +"%' and";
21 }
22 if (txt_qdrqdy.Text.Length >0)
23 {
24 WhereText +=" qdrq>='"+ txt_qdrqdy.Text.Trim() +"' and";
25 }
26 if (txt_qdrqxy.Text.Length >0)
27 {
28 WhereText +=" qdrq<'"+ txt_qdrqxy.Text.Trim() +"' and";
29 }
30 if (ddl_xmlx.SelectedValue.Length >0)
31 {
32 WhereText +=" xmlx='"+ ddl_cdbm.SelectedValue +"' and";
33 }
34 if (txt_htjedy.Text.Length >0)
35 {
36 WhereText +=" htje>='"+ txt_htjedy.Text.Trim() +"' and";
37 }
38 if (txt_htjexy.Text.Length >0)
39 {
40 WhereText +=" htje<'"+ txt_htjexy.Text.Trim() +"' and";
41 }
42 if (rbl_xmgm.SelectedValue.ToString().Length >0)
43 {
44 WhereText +=" xmgm='"+ rbl_xmgm.SelectedValue +"' and";
45 }
46 if (ddl_khjl.SelectedValue !="0")
47 {
48 WhereText +=" khjl='"+ ddl_khjl.SelectedValue +"' and";
49 }
50 if (ddl_cdbm.SelectedValue !="0")
51 {
52 WhereText +=" cdbm='"+ ddl_cdbm.SelectedValue +"' and";
53 }
54 if (ddl_xmjl.SelectedValue !="0"&& ddl_xmjl.SelectedValue !="")
55 {
56 WhereText +=" xmjl='"+ ddl_xmjl.SelectedValue +"' and";
57 }
58
59 if (WhereText.Length>0)
60 {
61 cmdText += WhereText.Substring(0, WhereText.Length -4);//去掉最后一个and
62  
63 }
64
65 string strCon ="server=.;database=tangge;uid=sa;pwd=sa";
66 SqlConnection conn =new SqlConnection(strCon);
67 conn.Open();
68 DataSet ds =new DataSet();
69 SqlCommand cmd =new SqlCommand(cmdText, conn);//cmdText是sql语句,con是连接数据库
70   SqlDataAdapter da =new SqlDataAdapter(cmd);
71 da.Fill(ds);
72 GridView1.DataSource = ds;
73 GridView1.DataBind();
74 conn.Close();
75
76 }
77  
posted @ 2010-11-13 00:26  【唐】三三  阅读(2875)  评论(3编辑  收藏  举报