GridView应用随笔

1、 数据绑定

  GridView可以使用数据源控件和设置控件的DataSource属性来绑定数据,这里主要讲设置DataSource属性来绑定。

  1、写一个返回值为DataSet或者DataTable的方法用于提取数据库中的数据,并在后台把GridView的DataSource属性设置为该DataSet或DataTable;

  2、前台编辑GridView的模板,这里可以使用asp:BoundField或者asp:TemplateField来显示数据,两者之间的区别是BoundField只用于显示数据,不能设置其样式,而TemplateField不仅可以显示数据还能往里面写控件,比如DropDownList、RadioButtonList等等,然后设置HeaderText等属性;再在ItemTemplate里用<%#Eval(“”)%>把DataSource里的列名绑定好。

  3、执行DataBind方法,运行一下,应该就可以显示查到的数据了。

  注:这里有一个小插曲,当在后台设置完DataSource和前台绑定完数据后会显示两遍数据,即DataSource和Eval各显示一遍,这时需要设置GridView的AutoGenerateColumns="False" 就行了。

  注:格式化绑定数据:<%#string.Format("[{0}]{1}",Eval("userid").ToString().Trim(),Eval("username")) %>

2、 修改

  修改有点小麻烦,需要写几个事件。

  1、 前台写编辑模板,即EditItemTemplate,把编辑状态下每个单元格的显示方式都写好,比如编辑时需要以DropDownList形式或者TextBox形式都写在EditItemTemplate模板中,ID、初始值都要设置好;asp:TemplateField没有ReadOnly属性,所以不想此项修改的话可以写成Label;

  2、 写GridView1_RowEditing事件如下:

  GridView1.EditIndex = e.NewEditIndex;

  Bind();//绑定数据的方法

  3、 写GridView1_RowCanCelingEdit事件如下:

  GridView1.EditIndex = -1;

  Bind();//绑定数据的方法

  4、 写GridView1_RowUpdating事件如下:

  string sql = "update Producttouser set";

      string userid=((TextBox)(GridView1.Rows[e.RowIndex].FindControl("useridTxt"))).Text.ToString().Trim();

      sql += " userid='" + userid.Substring(1, userid.IndexOf(']')-1);

      sql += "',centeruserid=" + ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("centeruseridTxt"))).Text.ToString().Trim();

      sql += ",productname='" + ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("productnameTxt"))).Text.ToString().Trim();

      sql += "',outprice=" + ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("outpriceTxt"))).Text.ToString().Trim();

      sql += " where productid=" + GridView1.DataKeys[e.RowIndex]["productid"].ToString().Trim();

        SQLHelper.MyNonQuery(sql);//DataKeys是获取GridView数据的好办法,需要在 GridView里添加一个属性:DataKeyNames="productid",如果需要多个 DataKeys就在DataKeyNames里添加多个,中间用逗号隔开

        GridView1.EditIndex = -1;

        Bind();

3、 批量删除

  批量删除即是在每一行的第一单元格放一个CheckBox,最下面放两个按钮,一个是反选另一个是删除按钮。

  1、 在前台模板的最前方写一个asp:TemplateField,里面放一个CheckBox,设置其ID;

  2、 在反选按钮的Click事件中写如下代码:

  for (int i = 0; i < GridView1.Rows.Count; i++)

        {

    CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("cb");

    //cb是CheckBox的ID属性值

        if (cb.Checked == true)

        {

           cb.Checked = false;

            }

         else

         {

           cb.Checked = true;

          }

      }

  注:这种反选的效果不好,选的时候页面会刷新,用Jquery实现最好。

  3、 在删除按钮的Click事件中写如下代码:

  string sql = "delete from Producttouser where";

  string where = "";

  for (int i = 0; i < GridView1.Rows.Count; i++)

   {

      CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("cb");

      if (cb.Checked == true)

        {

         string productid = GridView1.DataKeys[i]["productid"].ToString().Trim();

   //DataKeys是获取GridView数据的好办法,需要在 GridView里添加一个属性:DataKeyNames="productid",如果需要多个 DataKeys就在DataKeyNames里添加多个,中间用逗号隔开

         where += " productid=" + productid+ " or";

        }

    }

        if (where == "")

        {

          Response.Write("<script>alert('您没有选中任何项!')</script>");

        }

        else

        {

            where = where.Substring(0,where.Length-3);

            sql += where;

            SQLHelper.MyNonQuery(sql);

            Bind();

        }

  4、如果想要在删除之前让用户确认一下,可设置按钮的OnClientClick事件如下:

  OnClientClick="return confirm('你确定要删除吗?')";

4、 分页

  1、 GridView自带的有分页功能,设置属性AllowPaging="True"即开启分页功能,还可设置PageSize等属性;

  2、 写GridView1_ PageIndexChanging事件如下:

  GridView1.PageIndex = e.NewPageIndex;

  GridView1.EditIndex = -1;//防止用户点击编辑按钮再点击下一页时出现编辑状态的小Bug

      Bind();

5、排序

  常用的排序是用户点击列名后数据按该列递增或递减排序;

  1、 设置GridView的AllowSorting="True" 即开启排序功能;

  2、 在前台的每个模板里设置SortExpression属性为该列列名;

  3、 在Page_Load事件中写如下代码:

  if (!Page.IsPostBack)

        {

            ViewState["SortOrder"] = "userid";

            ViewState["OrderDire"] = "ASC";

            Bind();

        }

  4、 写GridView1_Sorting事件如下:

  string sPage = e.SortExpression;

        if (ViewState["SortOrder"].ToString() == sPage)

        {

            if (ViewState["OrderDire"].ToString() == "Desc")

                ViewState["OrderDire"] = "ASC";

            else

                ViewState["OrderDire"] = "Desc";

        }

        else

        {

            ViewState["SortOrder"] = e.SortExpression;

        }

  Bind();

  5、 Bind方法代码如下:

   string sql = "select top 200 Producttouser.userid,username,centeruserid,productid,productname,outprice,brandid,maintype,barcode from Producttouser,

userbaseinfo where Producttouser.userid=userbaseinfo.userid and nowcancel=0";

        DataTable dt = SQLHelper.ExecuteDataTable(sql);

        DataView dv = dt.DefaultView;

        if (ViewState["SortOrder"] != null && ViewState["OrderDire"] != null)

        {

            string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];

            dv.Sort = sort;

        }

        GridView1.DataSource = dv;

        GridView1.DataBind();

6、 全选/反选

  上次说到全选和反选是用的服务器控件,缺点很明显,点击按钮的时候页面会刷新,效率也不高,这次用Jquery实现的全选/反选就很好了,只需要设置反选按钮的Click事件即可,这里的CheckBox还是服务器控件,所以就用了Type属性获取,代码如下:

    function ReCheck() {

            $("#GridView1 input[type='checkbox']").each(function () {

                if (this.checked) {

                    this.checked = false;

                }

                else {

                    this.checked = true;

                }

            })

        }

 7、条件查询

  实际工作中经常会遇到让用户选择条件进行查询数据,效果如图:

   

  这实际上就是一条SQL语句的事儿,但笔者在实现这个小功能时还是遇到了些问题。

  这里用的都是服务器端控件,后台获取到Ddl和Txt的数据后写了一条查询语句如下:

  select top 200 Producttouser.userid,username,centeruserid,productid,productname,outprice,brandid,maintype,barcode from Producttouser,

userbaseinfo where Producttouser.userid=userbaseinfo.userid and nowcancel=0 and @searchType=@id

  然后传入参数执行查询,但一直查不出数据,最后把@searchType换成字符串拼接才算 查出了数据,最后得出结论,参数化SQL语句中的参数只能是具体的值,而不是能列名, 这里我就是把查询条件中的列名(searchType)当做参数处理了,也就查不到数据了(吐 槽一下:SQLServer你TM就不会报个错么?)

 

 

posted on 2014-03-11 16:32  七步、  阅读(292)  评论(0编辑  收藏  举报