EnableViewState="false"的DataGrid分页

类别:.NET开发 点击:0 评论:0 推荐:

用DataGrid默认的分页方式有两个小问题

1.要有viewstate,由你表的数据量决定,一般情况下较大
2.用的是PostBack方式,刷新的时候提示是否要重发消息

所以改为取消viewstate在OnItemCreated生成HyperLink 方式,避免了以上两个问题

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
 public void ItemCreated(Object sender, DataGridItemEventArgs e) {
  ListItemType elemType = e.Item.ItemType;
  if (elemType == ListItemType.Pager)
  {
   TableCell pager = (TableCell) e.Item.Controls[0];
   for (int i=0; i<pager.Controls.Count; i+=2)
   {
    Control o = pager.Controls[i];
    if (o is LinkButton)
    {
     LinkButton lb = (LinkButton) o;
     HyperLink hl=new HyperLink();
     hl.NavigateUrl=Request.Path  + "?page="+lb.CommandArgument;
     hl.Text="[ "+lb.Text+" ]";
     pager.Controls.RemoveAt(i);
     pager.Controls.AddAt(i,hl);
    }
    else
    {
     Label l = (Label) o;
     l.Text = "Page " + l.Text;
    }
   }
  }
 }
    protected void Page_Load(Object sender, EventArgs e)
    {
     if(!Page.IsPostBack){
      int pageIndex=0;
      try{pageIndex=Int32.Parse(Request["page"])-1;}catch(Exception ex){}
      Response.Write(MyDataGrid.PageCount);
      MyDataGrid.CurrentPageIndex=pageIndex;
      BindData();
     }
    }

 void BindData(){
//绑定数据库,略       
 }
</script> 
<HTML>
  <body>
    <form id="Form1" method="post" runat="server">
      <asp:datagrid id="MyDataGrid" runat="server" EnableViewState="false"  AllowPaging="True" PageSize="10"
        OnItemCreated="ItemCreated"
  PagerStyle-BackColor="#FFFFFF"
    PagerStyle-HorizontalAlign="Right"
    PagerStyle-Mode="NumericPages">
     </asp:datagrid>
   </form>
  </body>
</HTML>

本文地址:http://com.8s8s.com/it/it45843.htm