海军资料

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
   还是先看一下效果吧.
     

怎么样,是不是很酷?

下面一步说明如何实现:

写一个自定义控件,继承自System.Web.UI.WebControl.GridView,然后对其进行扩展。

分页的实现:

重写OnRowCreate方法,对PagerRow进行特殊处理,清空里面的控件,加入自己的控件。首页,尾页,上一页,下一页的做法是,往PagerRow中添加四个LinkButton,CommandName设成"Page",CommandArgument分别设成"First","Last","Prev","Next".相应的Text或者Image可直接使用PagerSettings属性中的数据。

直接跳转页和每页记录条数的实现相对麻烦一些。加入两个DropDownList控件,往里面填充数据,并在此类中处理它们的OnSelectedIndexChange事件,重置PageIndex和PageSize.

排序图标的实现:

同样在OnRowCreate方法中,对HeaderRow进行特殊处理,可根据SortExpression属性找到当前正在进行排序的列,根据SortDirection属性得到排序的顺序,根据这两个属性往特定的列添加特定的图标。

滚动条的实现:

重写RenderContents方法,改变原有的HTML流布局。如果不重写,原来的布局如下:

  
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace GridViewTest.Components
{
    /**/
    /// <summary>
    /// 自定义分页相关
    /// </summary>
    public class Paging
    {
        /**/
        /// <summary>
        /// 自定义分页样式
        /// </summary>
        public enum PagingStyleCollection
        {
            /**/
            /// <summary>
            /// 不用自定义分页样式
            /// </summary>
            None,
            /**/
            /// <summary>
            /// 默认自定义分页样式
            /// </summary>
            Default
        }
    }
    /// <summary>
    /// 统一样式等以方便整个程序使用的GridView。
    /// ziyan (http://ziyan22.cnblogs.com/)  2007-08-03
    /// 欢迎使用,希望保留版权
    /// </summary>
    [DefaultProperty("PageSize"),
    ToolboxData("<{0}:ZHJGridView runat=server></{0}:ZHJGridView>")]
    public class ZHJGridView : GridView
    {
        private int delColumnIndex=-1;
  string deletePromptText="确实要删除指定的记录吗?";
  bool fixHeader=false;
  bool addSequenceColumn=false;
  string sri;
  string funcSR;
  string funcMout;
  string funcMover;
        private string edittext1;
        private string edittext2;
        private string edittext3;
        private bool edit=false;
        private bool del = false;
        private string sortexpressioncust;
        Button But_Ok = new Button();
        TextBox Txt_Fild = new TextBox();
        private Label la_mes = new Label();
        private int RecordCount = 0;
        /// <summary>
        /// 是否拥有删除权限
        /// </summary>
        public bool Del
        {
            get { return del; }
            set { del = value; }
        }
        /// <summary>
        /// 是否拥有编辑权限
        /// </summary>
        public bool Edit
        {
            get { return edit; }
            set { edit = value; }
        }
       
        /// <summary>
        /// 排序表达式
        /// </summary>
        public string  SortExpressionCust
        {
            get { return sortexpressioncust; }
            set { sortexpressioncust = value; }
        }
       
        /// <summary>
        /// 编辑按钮弹出页面的路径 返回的路径和页码
        /// </summary>
        public string EditText1
        {
            get { return edittext1; }
            set { edittext1 = value; }
        }
        /// <summary>
        /// 辑按钮弹出页面的路径 返回的路径和页码
        /// </summary>
        public string EditText2
        {
            get { return edittext2; }
            set { edittext2 = value; }
        }
        public override object DataSource
        {
            get
            {
                return base.DataSource;
            }
            set
            {
                base.DataSource = value;
                if (value != null)
                {
                    if (DataSource is DataSet)
                        RecordCount = ((DataSet)DataSource).Tables[0].Rows.Count;
                    if (DataSource is ICollection)
                        RecordCount = ((ICollection)DataSource).Count;
                    if (DataSource is DataTable)
                        RecordCount = ((DataTable)DataSource).Rows.Count;
                    if (DataSource is DataView)
                        RecordCount = ((DataView)DataSource).Table.Rows.Count;
                }

            }
        }
         private Paging.PagingStyleCollection _pagingStyle;
         /// <summary>
        /// 自定义分页样式
        /// </summary>
        [Description("自定义分页样式"), DefaultValue(""), Category("扩展")]
        public Paging.PagingStyleCollection PagingStyle
        {
            get { return _pagingStyle; }
            set { _pagingStyle = value; }
        }
         /**********************************************************************************/
        /// <summary>
        /// 排序顺序
        /// </summary>
        public SortDirection GridViewSortDirection
        {
            get
            {
                if (ViewState["sortDirection"] == null)
                    ViewState["sortDirection"] = SortDirection.Ascending;
                return (SortDirection)ViewState["sortDirection"];
            }
            set { ViewState["sortDirection"] = value; }
        }

        /**//// <summary>
        /// 是否启用或者禁止多列排序
        /// </summary>
        [
          Description("是否启用多列排序功能"),
          Category("排序"),
          DefaultValue("true"),
        ]
         public bool AllowMultiColumnSorting
         {
             get
             {
                 object o = ViewState["EnableMultiColumnSorting"];
                 if(o!=null)
                 {
                     return bool.Parse(o.ToString());
                 }else
                 {
                     return false;
                 }
             }
             set
             {
                 AllowSorting = true;
                 ViewState["EnableMultiColumnSorting"] = value;
             }
       }
       /**//// <summary>
       /// 升序时显示图标
       /// </summary>
       [
         Description("升序时显示图标"),
         Category("排序"),
         Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor)),
         DefaultValue(""),
 
        ]
        public string SortAscImageUrl
        {
            get
            {
                object o = ViewState["SortImageAsc"];
                return (o != null ? o.ToString() : "");
            }
            set
            {
                ViewState["SortImageAsc"] = value;
            }
        }
        /**//// <summary>
        /// 降序时显示图标
        /// </summary>
        [
          Description("降序时显示图标"),
          Category("排序"),
           Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor)),
           DefaultValue(""),
         ]
         public string SortDescImageUrl
         {
             get
             {
                 object o = ViewState["SortImageDesc"];
                 return (o != null ? o.ToString() : "");
             }
             set
             {
                 ViewState["SortImageDesc"] = value;
             }
         }
      
       
       
        /// <summary>
        /// 编辑按钮弹出页面的路径 返回的路径和页码
        /// </summary>
        public string EditText3
        {
            get { return edittext3; }
            set { edittext3 = value; }
        }
       
  /// <summary>
  /// 删除记录时的提示文字
  /// </summary>
  public string DeletePromptText
  {
   get { return deletePromptText; }
   set { deletePromptText = value; }
  }
        /// <summary>
        /// 是否加载列标题样式
        /// </summary>
  public bool FixHeader
  {
   get { return fixHeader; }
   set { fixHeader = value; }
  }
  /// <summary>
  /// 是否插入序号列
  /// </summary>
  public bool AddSequenceColumn
  {
   get { return addSequenceColumn; }
   set { addSequenceColumn = value; }
  }
  protected override void OnLoad(EventArgs e)
  {
   if(!Page.IsClientScriptBlockRegistered("gridFunctions"))
    Page.RegisterClientScriptBlock(this.UniqueID+"_rowFunc","<script language=\"Javascript\">/*ziyan 2006-12-16*/var "+sri+";function "+funcSR+"(rowEl){if(event.srcElement.tagName!='A'){if("+sri+"==rowEl.rowIndex){rowEl.runtimeStyle.backgroundColor=rowEl.style.backgroundColor;rowEl.runtimeStyle.color=rowEl.style.color;"+sri+"=-1;setLinkClass(rowEl,false);}else {if("+sri+">-1){var oldRow=rowEl.parentElement.rows["+sri+"];oldRow.runtimeStyle.backgroundColor=oldRow.style.backgroundColor;oldRow.runtimeStyle.color=oldRow.style.color;setLinkClass(oldRow,false);}rowEl.runtimeStyle.backgroundColor='highlight';rowEl.runtimeStyle.color='highlighttext';"+sri+"=rowEl.rowIndex;setLinkClass(rowEl,true);}}}function "+funcMout+"(rowEl){if("+sri+"!=rowEl.rowIndex){rowEl.runtimeStyle.backgroundColor=rowEl.style.backgroundColor;}}function "+funcMover+"(rowEl){ if("+sri+"!=rowEl.rowIndex){rowEl.runtimeStyle.backgroundColor='#FFFFAA';}}function setLinkClass(rowEl,isSelected){for(i=0;i<rowEl.cells.length;i++){for(j=0;j<rowEl.cells[i].children.length;j++){if(rowEl.cells[i].children[j].tagName==\"A\"){if(isSelected){rowEl.cells[i].children[j].className=\"whitelink\";}else{rowEl.cells[i].children[j].className=\"\";}}}}}</script>");
            // 查找ObjectDataSource
            ObjectDataSource ods = Parent.FindControl(this.DataSourceID) as ObjectDataSource;
            if (ods != null)
            {
                ods.Selected += new ObjectDataSourceStatusEventHandler(ods_Selected);
            }
            base.OnLoad(e);
  }
        protected int? _recordCount = null;
        /**/
        /// <summary>
        /// 计算总记录数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ods_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {
            if (e.ReturnValue is IListSource)
            {
                _recordCount = ((IListSource)e.ReturnValue).GetList().Count;
            }
        }
  /// <summary>
  /// 重写OnInit方法,找出删除按钮所在列的索引值以便自动添加删除确认代码
  /// ziyan 2006-12-16
  /// </summary>
  /// <param name="e"></param>
  protected override void OnInit(EventArgs e)
  {
            base.OnInit(e);
            sri = this.ClientID + "_sri";
            funcSR = this.ClientID + "_sr";
            funcMout = this.ClientID + "_mout";
            funcMover = this.ClientID + "_mover";
            for (int i = 0; i < this.Columns.Count; i++)
            {
                this.delColumnIndex = i;
            }
  }
        public ZHJGridView()
  {
   this.HeaderStyle.HorizontalAlign=HorizontalAlign.Center;
   this.HeaderStyle.Font.Bold=true;
   this.HeaderStyle.BackColor=ColorTranslator.FromHtml("#C0C0FF");
   this.PagerStyle.BackColor=ColorTranslator.FromHtml("#E7E7FF");
   this.PagerStyle.ForeColor=ColorTranslator.FromHtml("#4A3C8C");
   this.PagerStyle.HorizontalAlign=HorizontalAlign.Left;
   this.BorderStyle=BorderStyle.Solid;
   this.BorderWidth=Unit.Pixel(1);
   this.BorderColor=ColorTranslator.FromHtml("#3366CC");
   this.CellPadding=4;
   this.AutoGenerateColumns=false;
   this.Style.Add("margin-left","2px");
   this.PageSize=10;
   this.Width=Unit.Percentage(99);
  }
     
         protected override void OnSorting(GridViewSortEventArgs e)
         {
            
             if (GridViewSortDirection == SortDirection.Ascending)
             {
                 GridViewSortDirection = SortDirection.Descending;
                 e.SortExpression = e.SortExpression + " DESC";
             }
             else
             {
                 GridViewSortDirection = SortDirection.Ascending;
                 e.SortExpression = e.SortExpression + " ASC";
                
             }
            
          
             base.OnSorting(e);
          
       }
        protected override void OnRowCreated(GridViewRowEventArgs e)
  {
            if (e.Row.RowType == DataControlRowType.Header )
            {
                DisplaySortOrderImages(SortExpressionCust, e.Row);
                this.CreateRow(0, 0, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
            }
            if (this.AllowPaging)
            {
                IEnumerable dataSource = this.DataSource as IEnumerable;
                if (dataSource != null)
                {
                    IEnumerator iEnum = dataSource.GetEnumerator();
                    int i = 0;
                    while (iEnum.MoveNext())
                    {
                        i++;
                    }
                    this.Page.Visible = (i > 0);
                }
            }
           
   //固定表头 ziyan 2006-12-16
            if (e.Row.RowType == DataControlRowType.Header && fixHeader)
   {
                foreach (TableCell cell in e.Row.Cells)
    {
     cell.CssClass="fhc";
    }
   }
            else if (e.Row.RowType == DataControlRowType.Pager && this.AllowPaging)
            {
                #region //处理分页
                LinkButton First = new LinkButton();
                LinkButton Prev = new LinkButton();
                LinkButton Next = new LinkButton();
                LinkButton Last = new LinkButton();
                TableCell tc = new TableCell();
                e.Row.Controls.Clear();
                tc.Height = 30; //分页栏的高度
                //添加总记录数
                tc.Controls.Add(new LiteralControl("每页"));
                tc.Controls.Add(new LiteralControl("<font color='red'>"+PageSize.ToString()+"</font>"));
                tc.Controls.Add(new LiteralControl("条"));
                tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
                tc.Controls.Add(new LiteralControl("共"));
                tc.Controls.Add(new LiteralControl("<font color='red'>" + RecordCount.ToString() + "</font>"));
                tc.Controls.Add(new LiteralControl("条"));
                tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;"));
                tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;"));
                tc.Controls.Add(new LiteralControl("第"));
                tc.Controls.Add(new LiteralControl("<font color='red'>"+(PageIndex + 1).ToString()+"</font>"));
                tc.Controls.Add(new LiteralControl("页"));
                tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
                tc.Controls.Add(new LiteralControl("共"));
                tc.Controls.Add(new LiteralControl("<font color='red'>"+PageCount.ToString()+"</font>"));
                tc.Controls.Add(new LiteralControl("页"));
                tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"));
              
                if (!String.IsNullOrEmpty(PagerSettings.FirstPageImageUrl))
                {
                    First.Text = "<img src='" + ResolveUrl(PagerSettings.FirstPageImageUrl) + "' border='0'/>";
                }
                else
                {
                    First.Text = PagerSettings.FirstPageText;
                }
                First.CommandName = "Page";
                First.CommandArgument = "First";
                First.Font.Underline = false;
                if (!String.IsNullOrEmpty(PagerSettings.PreviousPageImageUrl))
                {
                    Prev.Text = "<img src='" + ResolveUrl(PagerSettings.PreviousPageImageUrl) + "' border='0'/>";
                }
                else
                {
                    Prev.Text = PagerSettings.PreviousPageText;
                }
                Prev.CommandName = "Page";
                Prev.CommandArgument = "Prev";
                Prev.Font.Underline = false;

                if (!String.IsNullOrEmpty(PagerSettings.NextPageImageUrl))
                {
                    Next.Text = "<img src='" + ResolveUrl(PagerSettings.NextPageImageUrl) + "' border='0'/>";
                }
                else
                {
                    Next.Text = PagerSettings.NextPageText;
                }
                Next.CommandName = "Page";
                Next.CommandArgument = "Next";
                Next.Font.Underline = false;
                if (!String.IsNullOrEmpty(PagerSettings.LastPageImageUrl))
                {
                    Last.Text = "<img src='" + ResolveUrl(PagerSettings.LastPageImageUrl) + "' border='0'/>";
                }
                else
                {
                    Last.Text = PagerSettings.LastPageText;
                }
                Last.CommandName = "Page";
                Last.CommandArgument = "Last";
                Last.Font.Underline = false;
                if (this.PageIndex <= 0)
                {
                    First.Enabled = Prev.Enabled = false;
                }
                else
                {
                    First.Enabled = Prev.Enabled = true;
                }
                tc.Controls.Add(First);
                tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
                tc.Controls.Add(Prev);
                tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
                // 当前页左边显示的数字分页按钮的数量
                int rightCount = (int)(PagerSettings.PageButtonCount / 2);
                // 当前页右边显示的数字分页按钮的数量
                int leftCount = PagerSettings.PageButtonCount % 2 == 0 ? rightCount - 1 : rightCount;
                for (int i = 0; i < PageCount; i++)
                {
                    if (PageCount > PagerSettings.PageButtonCount)
                    {
                        if (i < PageIndex - leftCount && PageCount - 1 - i > PagerSettings.PageButtonCount - 1)
                        {
                            continue;
                        }
                        else if (i > PageIndex + rightCount && i > PagerSettings.PageButtonCount - 1)
                        {
                            continue;
                        }
                    }
                    if (i == PageIndex)
                    {
                        tc.Controls.Add(new LiteralControl("<span style='color:red;font-weight:bold'>" + (i + 1).ToString() + "</span>"));
                    }
                    else
                    {
                        LinkButton lb = new LinkButton();
                        lb.Text = (i + 1).ToString();
                        lb.CommandName = "Page";
                        lb.CommandArgument = (i + 1).ToString();
                        tc.Controls.Add(lb);
                    }
                    tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
                }
                if (this.PageIndex >= PageCount - 1)
                {
                    Next.Enabled = Last.Enabled = false;
                }
                else
                {
                    Next.Enabled = Last.Enabled = true;
                }
                tc.Controls.Add(Next);
                tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
                tc.Controls.Add(Last);
                tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
                tc.ColumnSpan = this.Columns.Count;
                //添加跳转查找功能
                Txt_Fild.Width = 40;
                Txt_Fild.Text = "";
                Txt_Fild.ForeColor = ColorTranslator.FromHtml("red");
                tc.Controls.Add(Txt_Fild);
                la_mes.Visible = false;
                la_mes.ForeColor = ColorTranslator.FromHtml("red");
                la_mes.Width = 20;
                tc.Controls.Add(la_mes);
                tc.Controls.Add(new LiteralControl("&nbsp;"));
                But_Ok.Text = "转到";
                But_Ok.Width = 40;
                tc.Controls.Add(But_Ok);
                tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
                e.Row.Controls.Add(tc);
                But_Ok.Click += new System.EventHandler(But_Ok_Click);
                #endregion
            }
            base.OnRowCreated(e);
  }
       
        /// <summary>
        /// 转到按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void But_Ok_Click(object sender,EventArgs e)
        {  
            if(Txt_Fild.Text.Trim()=="")
            {
                la_mes.Visible = true;
                la_mes.Text = "请填写转到页数";
                Txt_Fild.Text = "0";
            }
            else
            {
                try
                {
                    int.Parse(Txt_Fild.Text.Trim());
                }
                catch(Exception ex)
                {
                    la_mes.Visible = true;
                    la_mes.Text = "请填写真实的页码";
                    Txt_Fild.Text = "0";
                }
            }
            if(int.Parse(Txt_Fild.Text.Trim())<1)
            {
                Txt_Fild.Text = "1";
            }
            la_mes.Visible = true;
            But_Ok.CommandName = "Page";
            But_Ok.CommandArgument = Txt_Fild.Text.Trim();
        }
  /// <summary>
  /// 当删除数据时,如果当前页只有一条记录并且总页数大于一,则跳到前一页,以免当前页因无数据显示而出错(Webdiyer 2006-1-4)
  /// </summary>
  /// <param name="e"></param>
        protected override void OnRowDeleted(GridViewDeletedEventArgs e)
  {
            if (this.Rows.Count == 1 && this.PageIndex > 0)
    this.PageIndex --;
   base.OnRowDeleted (e);
  }

  /// <summary>
  /// 据数据源中项的总数判断是否显示分页按钮项
  /// ziyan 2005-12-16
  /// </summary>
  /// <param name="e"></param>
        protected override void OnRowDataBound(GridViewRowEventArgs e)
  {
   if(this.AllowPaging)
   {
    IEnumerable dataSource=this.DataSource as IEnumerable;
    if(dataSource!=null)
    {
     IEnumerator iEnum=dataSource.GetEnumerator();
     int i=0;
     while(iEnum.MoveNext())
     {
      i++;
     }
                    this.Page.Visible = (i >0);
    }
   }
   //对于int、decimal及DateTime等类型的数据,若其值为对应的数据类型的最小值则不显示 ziyan 2006-12-16注
   string[] hv=new string[9];
   hv[0]=int.MinValue.ToString();
   hv[1]=decimal.MinValue.ToString();
   hv[2]=decimal.MinValue.ToString("0.00");  //指定两位小数格式
   hv[3]=decimal.MinValue.ToString("0.000");  //指定三位小数格式
   hv[4]=decimal.MinValue.ToString("0.0000");  //四位小数格式
   hv[5]=DateTime.MinValue.ToString();  //默认日期格式
   hv[6]=DateTime.MinValue.ToShortDateString(); //短日期格式
   hv[7]=DateTime.MinValue.ToString("yyyy年M月d日"); //指定日期格式
   hv[8]=DateTime.MinValue.ToString("yyyy年MM月dd日"); //自定义日期格式
   foreach(TableCell cell in e.Row.Cells)
   {
    if(Array.IndexOf(hv,cell.Text)>=0)
    {
     cell.Text="";
    }
   }
            if (e.Row.RowType == DataControlRowType.DataRow )
   {
    //鼠标移过行时背景变色及点击时选中行
                e.Row.Style.Add("cursor", "default");
                e.Row.Attributes["onmouseover"] = funcMover + "(this)";
                e.Row.Attributes["onmouseout"] = funcMout + "(this)";
                //e.Row.Attributes["onclick"] = funcSR + "(this)";
    //添加删除确认
    if(this.delColumnIndex>=0)
    {
                    try
                    {
                        ImageButton imb_Delete = (ImageButton)e.Row.Cells[0].FindControl("imb_Delete");
                        imb_Delete.Attributes.Add("onclick", "return confirm(\'" + deletePromptText + "\');");
                        imb_Delete.CommandArgument = e.Row.RowIndex.ToString();
                        if (this.Del == false)
                        {
                            imb_Delete.Visible = false;
                        }
                        else
                        {
                            imb_Delete.Visible = true;
                        }
                    }
          catch
        {
           
        }
                    HtmlImage htmlEdit = (HtmlImage)e.Row.FindControl("htmlEdit");
                    if (htmlEdit!=null)
                    {
                        try
                        {
                            int userID = (int)this.DataKeys[Convert.ToInt32(e.Row.RowIndex.ToString())].Value;
                            htmlEdit.Attributes.Add("onclick", EditText1 + userID + EditText2 + this.PageIndex + EditText3);
                        }
                        catch
                        {
                            long userID = (long)this.DataKeys[Convert.ToInt32(e.Row.RowIndex.ToString())].Value;
                            htmlEdit.Attributes.Add("onclick", EditText1 + userID + EditText2 + this.PageIndex + EditText3);
                        }
        
                      
                    }
                  
                    if (this.Edit == false)
                    {
                         if (htmlEdit!=null)
                         {
                            htmlEdit.Visible = false;
                         }
                     
                    }
                    else
                    {
                         if (htmlEdit!=null)
                        {
                            htmlEdit.Visible = true;
                        }
                      
                    }
                   
    }
              
                 
   }
   base.OnRowDataBound (e);
  }
       
       
         /**//// <summary>
      ///  获取排序表达式
      /// </summary>
      protected string GetSortExpression(GridViewSortEventArgs e)
      {
          string[] sortColumns = null;
          string sortAttribute = e.SortExpression;
          if ((sortAttribute != String.Empty) && (sortAttribute != null))
          {
              sortColumns = sortAttribute.Split(",".ToCharArray());
          }
          if (sortAttribute.IndexOf(e.SortExpression) > 0 || sortAttribute.StartsWith(e.SortExpression))
          {
              sortAttribute = ModifySortExpression(sortColumns, e.SortExpression);
          }
          else
          {
              sortAttribute += String.Concat(",", e.SortExpression, " ASC ");
          }
          return sortAttribute.TrimStart(",".ToCharArray()).TrimEnd(",".ToCharArray());
        }
        /**//// <summary>
        ///  修改排序顺序
        /// </summary>
        protected string ModifySortExpression(string[] sortColumns, string sortExpression)
        {
            string ascSortExpression = String.Concat(sortExpression, " ASC");
            string descSortExpression = String.Concat(sortExpression, " DESC");
            for (int i = 0; i < sortColumns.Length; i++)
            {
                if (ascSortExpression.Equals(sortColumns[i]))
                {
                   sortColumns[i] = descSortExpression;
                }
               else if (descSortExpression.Equals(sortColumns[i]))
               {
                   Array.Clear(sortColumns, i, 1);
               }
           }
            return String.Join(",", sortColumns).Replace(",,", ",").TrimStart(",".ToCharArray());
       }
       
          /**//// <summary>
       ///  获取当前的表达式对所选列进行排序
       /// </summary>
       protected void SearchSortExpression(string[] sortColumns, string sortColumn, out string sortOrder, out int sortOrderNo)
        {
            sortOrder = "";
            sortOrderNo = 1;
            if (sortColumns == null)
            {
                if (GridViewSortDirection == SortDirection.Ascending)
                {
                    sortOrder = "DESC";
                
                }
                else
                {
                    sortOrder = "ASC";
                

                }
            }
            else
            {
                    for (int i = 0; i < sortColumns.Length; i++)
                    {
                        if (sortColumns[i].StartsWith(sortColumn))
                        {
                            sortOrderNo = i + 1;
                            if (AllowMultiColumnSorting)
                            {
                                if (GridViewSortDirection == SortDirection.Ascending)
                                {
                                    sortOrder = "DESC";

                                }
                                else
                                {
                                    sortOrder = "ASC";
 
                                }
                            }
                            else
                            {
                                if (GridViewSortDirection == SortDirection.Ascending)
                                {
                                    sortOrder = "DESC";

                                }
                                else
                                {
                                    sortOrder = "ASC";
 
                                }
                            }
                        }
                    }
            }
        }
       
       
           /**//// <summary>
        ///  绘制升序降序的图片
        /// </summary>
        protected void DisplaySortOrderImages(string sortExpression, GridViewRow dgItem)
        {
            string[] sortColumns=null;
              
            if ((sortExpression != String.Empty) && (sortExpression != null))
            {
                sortColumns = sortExpression.Split(",".ToCharArray());
            }
           for (int i = 0; i < dgItem.Cells.Count; i++)
           {
               if (dgItem.Cells[i].Controls.Count > 0 && dgItem.Cells[i].Controls[0] is LinkButton)
                {
                    string sortOrder;
                    int sortOrderNo;
                    string column = ((LinkButton)dgItem.Cells[i].Controls[0]).CommandArgument;
                    SearchSortExpression(sortColumns, column, out sortOrder, out sortOrderNo);
                   if (sortOrderNo > 0)
                   {
                        string sortImgLoc = (sortOrder.Equals("ASC") ? SortAscImageUrl : SortDescImageUrl);
                       if (sortImgLoc != String.Empty)
                       {
                           System.Web.UI.WebControls.Image imgSortDirection = new System.Web.UI.WebControls.Image();
                           imgSortDirection.ImageUrl = sortImgLoc;
                           dgItem.Cells[i].Controls.Add(imgSortDirection);
                       }
                       else
                       {
                           if (AllowMultiColumnSorting)
                           {
                               Literal litSortSeq = new Literal();
                               litSortSeq.Text = sortOrderNo.ToString();
                               dgItem.Cells[i].Controls.Add(litSortSeq);
                           }
                       }
                   }
               }
           }
        }
 }
}

         

用法:
protected void Page_Load(object sender, EventArgs e)
        {
            if(!Page.IsPostBack)
            {
                GridViewDataBind();
            }
        }

        protected void GridView1_PageIndexChanging(object sender,GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            GridViewDataBind();
        }

        protected void GridViewDataBind()
        {
            string SQL = "select * from SYS_T_Menu";
            GridView1.DataSource = SqlHelper.GetQueryResult(SQL);
            GridView1.DataBind();
        }


















posted on 2007-08-03 22:53  周海军  阅读(2822)  评论(61编辑  收藏  举报