ViewState.Clear();
        string key = " ShowType=" + Request.QueryString["type"] + " and";
        if (TextBox1.Text.Length > 0)
            key += string.Format(" Address like '%{0}%' and", TextBox1.Text);
        if(TextBox2.Text.Length>0&&TextBox3.Text.Length==0)
            key += string.Format(" price > {0} and", TextBox2.Text);
        if (TextBox2.Text.Length == 0 && TextBox3.Text.Length > 0)
            key += string.Format(" price < {0} and", TextBox3.Text);
        if (TextBox2.Text.Length > 0 && TextBox3.Text.Length > 0)
            key += string.Format(" (price between {0} and {1}) and", TextBox2.Text,TextBox3.Text);
        if(DropDownList1.SelectedIndex>0)
            key += string.Format(" HouseType_ID={0} and", DropDownList1.SelectedValue);
        if(DropDownList2.SelectedIndex>0)
            key += string.Format(" Form='{0}' and", DropDownList2.SelectedItem.Text);
        if (DropDownList3.SelectedIndex > 0)
            key += string.Format(" Qu_ID={0} and", DropDownList3.SelectedValue);
        if (DropDownList4.SelectedIndex > 0)
            key += string.Format(" HuXing='{0}' and", DropDownList4.SelectedItem.Text);
        if (key.Length > 0)
            key = key.Substring(0, key.Length - 3);
        ViewState["key"] = key;
        Bind();
我很想知道为什么key = key.Substring(0, key.Length - 3);这一句为什么要减3  答辩急用

解决方案 »

  1.   

    本帖最后由 net_lover 于 2012-05-31 17:48:36 编辑
      

  2.   

    如果下面的TextBox都没有输入内容时,你的key就不会继续拼凑下去,那么你的查询语句就是
    string key = " ShowType=" + Request.QueryString["type"] + " and";
    这样,但是多了后面的and,会报语法错误的,所以从SQL字符串中去掉最后3个长度的字符,这样保证SQL语句能正常通过。
      

  3.   

    你的每一个条件后面都有and字符串.最后的目的是用数据库语句 同时也会多余一个and语句。sub掉最后的3位 也就是去掉了and 这时候得到的才是可以执行的数据库语句.希望能听明白.