原帖地址http://topic.csdn.net/u/20100807/14/cfb015bd-9498-4ff1-9b58-33c75aeb27b4.html我在原来的基础上增加了一点功能现在遇到如下几个问题:(1)查询按钮需要点击两次,才能显示正确结果。
(2)如果点了重选(主要工作就是撤销Gridview的绑定,以及Checkboxlist选项清空),再次选择时,如果上次已选的项本次未选,,点击查询时,在“ GridView1.DataBind();”处会提示对应的字段找不到。这个原因应该是与1有关系。
重选代码:protected void Button2_Click(object sender, EventArgs e)
    {
        for (Int32 i = 0; i < CheckBoxList1.Items.Count; i++)
        {
            CheckBoxList1.Items[i].Selected = false;
        }
        GridView1.DataSource = null;
        GridView1.DataBind();
        GridView1.Visible = false;    }查询代码:
 protected void Button1_Click(object sender, EventArgs e)
    {
        string ConStr = "server = .\\sqlexpress;user id=sa;pwd=sa;database = gridview";
        SqlConnection con = new SqlConnection(ConStr);        String sqlStr = "";
        for (Int32 i = 0; i < CheckBoxList1.Items.Count; i++)
        {
            if (CheckBoxList1.Items[i].Selected)
            {
                sqlStr += CheckBoxList1.Items[i].Value + ",";
            }
        }
        sqlStr = sqlStr.Trim(',');        String sql = "Select " + sqlStr + " from userinfo";
               SqlDataAdapter ada = new SqlDataAdapter(sql, con);
        con.Open();        DataSet ds = new DataSet();
        ada.Fill(ds, "tt");
        GridView1.Visible = true;
        GridView1.DataSource = ds;
        GridView1.DataBind();
        GridView1.Columns.Clear();        for (Int32 i = 0; i < CheckBoxList1.Items.Count; i++)
        {
            if (CheckBoxList1.Items[i].Selected)
            {                BoundField col = new BoundField();
                col.HeaderText = CheckBoxList1.Items[i].Text;
                col.DataField = CheckBoxList1.Items[i].Value;
                col.Visible = true;
                GridView1.Columns.Add(col);
            }
        }         con.Close();       
    }请各位高手赐教!