如何在DataGrid控件中实现自定义分页

    在一般情况下,DataGrid控件每次实现翻页操作时,都会将数据源中的数据重新调用一次,当数据中数据很多时,这样做就会很浪费系统资源和降低程序的执行效率.这时候我们一般通过自定义分页来解决这个问题.
    DataGrid控件的AllowCustomPaging属性用来获取或设置DataGrid控件是否允许自定义分页;VirtualItemCoun属性用来获取或设置在使用自定义分页时DataGrid中实际的项数.要实现自定义分页,必须将AllowPaging与AllowCustomPaging属性都设置为"True".
    在DataGrid中要实现自定义分页的关键是,使该控件仅仅调用当前显示所需要的数据源数据,在下面的例子中通过CurrentPageIndex和PageSize属性的值,在数据绑定时只取当前页需要的数据.
    (1)页面代码:
<% @ Page language = " c# "  Codebehind = " Main.aspx.cs "  AutoEventWireup = " false "  Inherits = " SissonDemo.Main "   %>
<! DOCTYPE HTML PUBLIC  " -//W3C//DTD HTML 4.0 Transitional//EN "   >
< HTML >
    
< HEAD >
        
< title > Main </ title >
        
< meta name = " GENERATOR "  Content = " Microsoft Visual Studio .NET 7.1 " >
        
< meta name = " CODE_LANGUAGE "  Content = " C# " >
        
< meta name = " vs_defaultClientScript "  content = " JavaScript " >
        
< meta name = " vs_targetSchema "  content = " http://schemas.microsoft.com/intellisense/ie5 " >
    
</ HEAD >
    
< body MS_POSITIONING = " GridLayout " >
        
< form id = " Form1 "  method = " post "  runat = " server " >
            
< FONT face = " 宋体 " >
                
< asp:DataGrid id = " DataGrid1 "  style = " Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 24px "  runat = " server "
                    Width
= " 792px "  Height = " 96px "  AllowCustomPaging = " True "  AllowPaging = " True "  PageSize = " 5 " >
                    
< PagerStyle Mode = " NumericPages " ></ PagerStyle >
                
</ asp:DataGrid ></ FONT >
        
</ form >
    
</ body >
</ HTML >
    (2)后台代码:
using  System;
using  System.Collections;
using  System.ComponentModel;
using  System.Data;
using  System.Drawing;
using  System.Web;
using  System.Web.SessionState;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.HtmlControls;
using  System.Data.SqlClient;

namespace  SissonDemo
{
    
/// <summary>
    
/// Main 的摘要说明。
    
/// </summary>

    public class Main : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.DataGrid DataGrid1;
         
int startIndex = 0;//用来保存当前页数据项的起始索引
        private void Page_Load(object sender, System.EventArgs e)
        
{
            
if(!IsPostBack)
            
{
                Bind();
//初始化时进行数据绑定
            }

            
        }

        
void Bind()//绑定数据方法
        {  //定义数据库连接对象
            SqlConnection cn=new SqlConnection("server=.;database=pubs;uid=sa;pwd=");
           
//创建数据适配对象
            SqlDataAdapter da=new SqlDataAdapter("select title_id ,title ,type, pub_id ,price,pubdate from titles",cn);
            
//创建DataSet对象
            DataSet ds=new DataSet();
            
try
            
{   //从指定的索引开始取PageSize条记录.
                da.Fill(ds,startIndex,DataGrid1.PageSize,"CurDataTable");
                da.Fill(ds,
"AllDataTable");//填充数据集合
                
//设置DataGrid控件实际要显示的项数
                DataGrid1.VirtualItemCount=ds.Tables["AllDataTable"].Rows.Count;
                
//进行数据绑定
                DataGrid1.DataSource=ds.Tables["CurDataTable"];
                DataGrid1.DataBind();
            
            }

            
catch
            
{
                Page.RegisterClientScriptBlock(
"","<script>alert('数据显示错误');</script>");
            }


        }


        
Web 窗体设计器生成的代码

        
private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
        
{
                
//设置DataGrid当前页的索引值为用户选择的页的索引
                DataGrid1.CurrentPageIndex=e.NewPageIndex;
                
//取得当前页为止总共有多少条记录,以便在下一页就从该记录开始读取
                startIndex=DataGrid1.PageSize*DataGrid1.CurrentPageIndex;
               
//取得绑定数据
                Bind();
        }

    }

}

    在这段程序中,首先在数据绑定时,设置DataGrid控件的VirtualItemCoun属性值为查询结果集中的记录总数,然后取得当前页要显示的数据,初始化时当前页显示的数据为从取到的数据的零位置开始,到DataGrid控件的PageSize属性的设定值为止的数据记录数.在分页操作中重新定义了取得下一页数据时的数据项的开始索引值,然后调用数据绑定方法把取到的新数据和DataGrid控件重新绑定.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要修改DataGrid控件的默认分页样式,可以使用自定义样式和模板。以下是一个示例,展示如何将分页按钮放置在DataGrid控件上方: ```xml <Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Style x:Key="DataGridStyle" TargetType="{x:Type DataGrid}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type DataGrid}"> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True"> <DockPanel> <StackPanel DockPanel.Dock="Top" Orientation="Horizontal" Margin="5"> <Button Content="First" Command="{x:Static DataGridCommands.SelectFirstPage}" CommandTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" /> <Button Content="Prev" Command="{x:Static DataGridCommands.SelectPreviousPage}" CommandTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" /> <TextBlock Text="{Binding DisplayTo}" Margin="5" VerticalAlignment="Center" /> <Button Content="Next" Command="{x:Static DataGridCommands.SelectNextPage}" CommandTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" /> <Button Content="Last" Command="{x:Static DataGridCommands.SelectLastPage}" CommandTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" /> </StackPanel> <ScrollViewer x:Name="DG_ScrollViewer" Focusable="false"> <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" /> </ScrollViewer> </DockPanel> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <Grid> <DataGrid Style="{StaticResource DataGridStyle}" /> </Grid> </Window> ``` 在此示例,我们创建了一个名为DataGridStyle的自定义样式,并将其应用于DataGrid控件。该样式的模板使用DockPanel将分页按钮放置在DataGrid控件的顶部,并使用ScrollViewer包装ItemsPresenter以实现滚动。 您还可以根据需要更改分页按钮的样式和位置,以满足您的具体需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值