Gridview标题头添加排序图片

向gridview标题头中添加排序图片,当点击某一个头标题时,在标题中出现升序箭头向上的图片,再点击一次时降序,在标题中出现箭头向下的图片,初始页面时在标题头中并不现实任何图片。

先定义好一个gridview,在gridview数据绑定结束后调下面方法。

protected void SortForImage(string sortDirection, string sortExpression)
        {
            if (!string.IsNullOrEmpty(sortExpression))
            {
                GridViewRow headRow = gvPlanedTools.HeaderRow;
                Image sortImage = new Image();
                if (sortDirection == "ASC")
                {
                    sortImage.ImageUrl = "~/_layouts/1033/IMAGES/WebPartImages/bullet_arrow_down.png";
                    sortImage.Style.Add("vertical-align", "bottom");
                }
                else
                {
                    sortImage.ImageUrl = "~/_layouts/1033/IMAGES/WebPartImages/bullet_arrow_up.png";
                    sortImage.Style.Add("vertical-align", "bottom");
                }
                int num = 0;
                foreach (DataControlField field in gvPlanedTools.Columns)
                {
                    if (field.SortExpression == sortExpression.ToString().Trim())
                    {
                        num = gvPlanedTools.Columns.IndexOf(field);
                    }
                }
                headRow.Cells[num].Controls.Add(sortImage);
            }
        }

另外在gridview sorting 方法中也需调用此方法,这里是在BindView()方法中调用上面添加图片排序的方法, 如:

protected void gvPlanedTools_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpression = e.SortExpression.ToString();
            string sortDirection = "ASC";
            if (sortExpression == gvPlanedTools.Attributes["SortExpression"])
            {
                sortDirection = (gvPlanedTools.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
            }
            gvPlanedTools.Attributes["SortExpression"] = sortExpression;
            gvPlanedTools.Attributes["SortDirection"] = sortDirection;
            BindView();
        }

BindView细节如下:

 private void BindView()
        {
            DataSet ds = GetDataSet();
            if (IsDateSetNullOREmpty(ds))
            {
                DataTable dt = ds.Tables[0];
                ViewState["PageCount"] = dt.Rows.Count.ToString();
                string sortExpression = gvPlanedTools.Attributes["SortExpression"];
                string sortDirection = gvPlanedTools.Attributes["SortDirection"];
                 if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    dt.DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }
                gvPlanedTools.DataSource = dt.DefaultView;
                gvPlanedTools.DataBind();
                SortForImage(gvPlanedTools.Attributes["SortDirection"], gvPlanedTools.Attributes["SortExpression"]);
            }
        }

 

 

posted @ 2013-08-13 18:38  Bradwarden  阅读(1500)  评论(0编辑  收藏  举报