自定义gridview

来源:互联网 发布:vb乘法表代码 编辑:程序博客网 时间:2024/05/03 05:15

using System;using System.Linq;using System.Collections.Generic;using System.Collections;using System.ComponentModel;using System.Drawing.Design;using System.Text;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace MattBerseth.WebControls{    /// <summary>    ///     /// </summary>    [ToolboxData("<{0}:GridView runat=server></{0}:GridView>")]    public class GridView : System.Web.UI.WebControls.GridView, IPageableItemContainer    {        /// <summary>        /// TotalRowCountAvailable event key        /// </summary>        private static readonly object EventTotalRowCountAvailable = new object();        /// <summary>        ///         /// </summary>        /// <param name="dataSource"></param>        /// <param name="dataBinding"></param>        /// <returns></returns>        protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)        {            int rows = base.CreateChildControls(dataSource, dataBinding);            //  if the paging feature is enabled, determine            //  the total number of rows in the datasource            if (this.AllowPaging)            {                //  if we are databinding, use the number of rows that were created,                //  otherwise cast the datasource to an Collection and use that as the count                int totalRowCount = dataBinding ? rows : ((ICollection)dataSource).Count;                //  raise the row count available event                IPageableItemContainer pageableItemContainer = this as IPageableItemContainer;                this.OnTotalRowCountAvailable(                    new PageEventArgs(                        pageableItemContainer.StartRowIndex,                         pageableItemContainer.MaximumRows,                         totalRowCount                    )                );                //  make sure the top and bottom pager rows are not visible                if (this.TopPagerRow != null)                {                    this.TopPagerRow.Visible = false;                }                if (this.BottomPagerRow != null)                {                    this.BottomPagerRow.Visible = false;                }            }            return rows;        }        #region IPageableItemContainer Interface        /// <summary>        ///         /// </summary>        /// <param name="startRowIndex"></param>        /// <param name="maximumRows"></param>        /// <param name="databind"></param>        void IPageableItemContainer.SetPageProperties(            int startRowIndex, int maximumRows, bool databind)        {            int newPageIndex = (startRowIndex / maximumRows);            this.PageSize = maximumRows;            if (this.PageIndex != newPageIndex)            {                bool isCanceled = false;                if (databind)                {                    //  create the event args and raise the event                    GridViewPageEventArgs args = new GridViewPageEventArgs(newPageIndex);                    this.OnPageIndexChanging(args);                    isCanceled = args.Cancel;                    newPageIndex = args.NewPageIndex;                }                //  if the event wasn't cancelled                //  go ahead and change the paging values                if (!isCanceled)                {                    this.PageIndex = newPageIndex;                    if (databind)                    {                        this.OnPageIndexChanged(EventArgs.Empty);                    }                }                if (databind)                {                    this.RequiresDataBinding = true;                }            }        }        /// <summary>        ///         /// </summary>        int IPageableItemContainer.StartRowIndex        {            get { return this.PageSize * this.PageIndex; }        }        /// <summary>        ///         /// </summary>        int IPageableItemContainer.MaximumRows        {            get { return this.PageSize; }        }        /// <summary>        ///         /// </summary>        event EventHandler<PageEventArgs> IPageableItemContainer.TotalRowCountAvailable        {            add { base.Events.AddHandler(GridView.EventTotalRowCountAvailable, value); }            remove { base.Events.RemoveHandler(GridView.EventTotalRowCountAvailable, value); }        }        /// <summary>        ///         /// </summary>        /// <param name="e"></param>        protected virtual void OnTotalRowCountAvailable(PageEventArgs e)        {            EventHandler<PageEventArgs> handler = (EventHandler<PageEventArgs>)base.Events[GridView.EventTotalRowCountAvailable];            if (handler != null)            {                handler(this, e);            }        }        #endregion    }} 


ASPX:

<%@ Page Language="C#" %><%@ Register Assembly="MattBerseth.WebControls" Namespace="MattBerseth.WebControls" TagPrefix="mb" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title>Untitled Page</title>    <link type="text/css" href="_assets/css/grid.css" rel="stylesheet" />    <link type="text/css" href="_assets/css/round.css" rel="stylesheet" />    <link type="text/css" href="_assets/css/core.css" rel="stylesheet" />      <script runat="server">                /// <summary>        ///         /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        protected void RowDataBound(object sender, GridViewRowEventArgs args)        {            MattBerseth.WebControls.GridView gridView = (MattBerseth.WebControls.GridView)sender;            if (gridView.SortExpression.Length > 0)            {                int cellIndex = -1;                foreach (DataControlField field in gridView.Columns)                {                    if (field.SortExpression == gridView.SortExpression)                    {                        cellIndex = gridView.Columns.IndexOf(field);                        break;                    }                }                if (cellIndex > -1)                {                    if (args.Row.RowType == DataControlRowType.Header)                    {                        //  this is a header row,                        //  set the sort style                        args.Row.Cells[cellIndex].CssClass +=                            (gridView.SortDirection == SortDirection.Ascending                            ? " sortasc" : " sortdesc");                      }                }            }                    }            </script>      </head><body>    <form id="form1" runat="server">    <asp:ScriptManager ID="scriptManager" runat="server" />    <asp:ObjectDataSource ID="odsProducts" runat="server" SelectMethod="Select" TypeName="ProductsDataObject" />    <div>        <p style="font-weight:bold; font-family:Tahoma;">This is a GridView Plus a DataPager!</p>        <div class="grid">            <div class="rounded">                <div class="top-outer"><div class="top-inner"><div class="top">                    <h2>Northwind Products</h2>                </div></div></div>                <div class="mid-outer"><div class="mid-inner"><div class="mid">                        <asp:UpdatePanel ID="updPanel" runat="server" UpdateMode="Conditional">                        <ContentTemplate>                            <mb:GridView                                 ID="gvProducts" runat="server" DataSourceID="odsProducts"                                OnRowDataBound="RowDataBound" AutoGenerateColumns="false" AllowPaging="true" AllowSorting="true"                                CssClass="datatable" CellPadding="0" CellSpacing="0" BorderWidth="0" GridLines="None"                            >                                <Columns>                                    <asp:BoundField                                         HeaderText="ID" DataField="ProductID" SortExpression="ProductID"                                        HeaderStyle-CssClass="first" ItemStyle-CssClass="first"                                     />                                    <asp:BoundField HeaderText="Name" DataField="ProductName" SortExpression="ProductName" />                                    <asp:BoundField HeaderText="Quantity" DataField="QuantityPerUnit" SortExpression="QuantityPerUnit" />                                    <asp:BoundField HeaderText="Unit Price" DataField="UnitPrice" SortExpression="UnitPrice" DataFormatString="{0:c}" ItemStyle-CssClass="money" />                                    <asp:BoundField HeaderText="In Stock" DataField="UnitsInStock" SortExpression="UnitsInStock" />                                    <asp:BoundField HeaderText="On Order" DataField="UnitsOnOrder" SortExpression="UnitsOnOrder" />                                </Columns>                                <RowStyle CssClass="row" />                            </mb:GridView>                              <!-- Notice this is outside the GridView -->                            <div class="pager">                                <asp:DataPager ID="pager" runat="server" PageSize="8" PagedControlID="gvProducts">                                    <Fields>                                        <asp:NextPreviousPagerField                                            ButtonCssClass="command"                                             FirstPageText="«" PreviousPageText="‹"                                                                                         RenderDisabledButtonsAsLabels="true"                                             ShowFirstPageButton="true" ShowPreviousPageButton="true"                                             ShowLastPageButton="false" ShowNextPageButton="false"                                        />                                         <asp:NumericPagerField                                            ButtonCount="7" NumericButtonCssClass="command"                                             CurrentPageLabelCssClass="current" NextPreviousButtonCssClass="command"                                        />                                        <asp:NextPreviousPagerField                                             ButtonCssClass="command"                                             LastPageText="»" NextPageText="›"                                             RenderDisabledButtonsAsLabels="true"                                             ShowFirstPageButton="false" ShowPreviousPageButton="false"                                             ShowLastPageButton="true" ShowNextPageButton="true"                                        />                                                                                </Fields>                                                            </asp:DataPager>                            </div>                                                     </ContentTemplate>                    </asp:UpdatePanel>                                         </div></div></div>            <div class="bottom-outer"><div class="bottom-inner"><div class="bottom"></div></div></div>                           </div>          </div>    </div>    </form></body></html>