65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 J# 在 ASP.NET DataGrid 中进行分页

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.18/5 (2投票s)

2005 年 6 月 15 日

2分钟阅读

viewsIcon

38859

downloadIcon

457

如何使用 J#.NET 在 ASP.NET 1.1 Grid 控件中实现分页。

引言

本文将向您展示如何使用 J#.NET 实现 ASP.NET DataGrid 控件的分页。如果表格中的项目列表非常庞大,并且由于某种原因我们无法在屏幕上显示所有信息,我们可以使用多页。就像电话簿一样,所有条目都不能列在同一页上。我们可以对 ASP.NET Grid 控件中的庞大项目列表执行完全相同的操作。添加多页。

开始吧!

打开 Visual Studio 并打开一个新的 J# ASP.NET Web 应用程序。在设计模式下将 DataGrid WebForms 控件添加到网页。右键单击该控件并选择“属性”。通过在“AllowPaging”属性中选择“True”来启用分页。您还可以设置“PageSize”属性中的页面大小。

限制

重要提示:您只能对实现 ICollection 接口的数据源使用分页。在本例中,我们将使用 System.Data.DataTable,因为它实现了此接口。DataReader 不实现 ICollection 接口。

数据源

在本例中,我们将显示来自 MS SQL 数据库的数据。如果页面请求不是回发,则执行数据库查找。

    private void Page_Load(Object sender, System.EventArgs e)
    {
        if ( !this.get_IsPostBack() )
        {
            // Initialize the DataGrid
            this.InitializeDataGrid();
        }
    }
    private void InitializeDataGrid( )
    {
        try
        {
            // DB connection string
            String _connectionString = 
               "Data Source=localhost\\MinDB;Initial " + 
               "Catalog=BMWCCN;User Id=aspnet;Password=aspnet";
            // Open a connection to the database using SQL login
            System.Data.SqlClient.SqlConnection _connection = 
              new System.Data.SqlClient.SqlConnection( _connectionString );
            
            // The sql statement
            String _sql = "SELECT * FROM Forum ORDER BY MeldingsId";
            
            // Creates a DataTable for the sql result.
            System.Data.DataTable _dataTable = new System.Data.DataTable( );
            
            // Uses a DataAdapter to get the data from the database.
            System.Data.SqlClient.SqlDataAdapter _adapter = 
              new System.Data.SqlClient.SqlDataAdapter( _sql, _connection );
            _adapter.Fill( _dataTable );
            
            // Sets the datasource and binds it to the DataGrid.
            this.DataGrid1.set_DataSource( _dataTable );
            this.DataGrid1.DataBind();

        }
        catch ( Exception ex )
        {
            this.get_Trace().Warn( ex.getMessage() );
        }
    }

PageIndexHander

将“页面索引更改”事件处理程序添加到控件。打开设计视图。右键单击它并选择“属性”。单击“属性”窗口中的闪电图标以显示所有事件处理程序。双击“PageIndexChanged”文本。Visual Studio 将在您的代码中添加一个处理程序。在索引页面处理程序中,您将告诉控件应该显示哪些数据。

    private void DataGrid1_PageIndexChanged (Object source, 
               System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
    {
        this.DataGrid1.set_CurrentPageIndex( e.get_NewPageIndex() );
        this.InitializeDataGrid( );
    }

这应该就是简单的分页所需要的一切。您可以使用“<”和“>”向前或向后移动。如果您希望使用数字而不是“<”和“>”来导航页面,请执行以下操作:在 Visual Studio 中切换到设计模式,右键单击该控件并选择“属性”,在“样式”下找到“PageStyle”,展开它并找到“Mode”,然后从“NextPrev”切换到“NumericPages”。

结论

在本文中,我们已经了解了如何为我们的 DataGrid ASP.NET 控件轻松实现分页支持。最重要的是记住数据源必须实现 ICollection 接口,并且请记住添加页面索引处理程序。

© . All rights reserved.