Multiple implementation methods and Performance Comparison of ASP. NET data Paging

Source: Internet
Author: User
Introduction:

The most common problem for dynamic website designers is to paging the data in the database. The disorganized data in the database is of no value. If we do not give such data a clear distinction between statistics and paging. Therefore, as a designer of dynamic web pages, we must provide visitors with the content to read and recognize as much as possible. Data paging is the most basic requirement.
Data paging is not a new topic. Almost all search engine websites and e-commerce websites have this feature. We tried to use the search term ASP to search for Google.com. We will get 5 million results! Imagine how huge and messy the 5 million results Goole gave us through a webpage, So Google paged the data, 10 records per page.
This article describes how to pagination data in the database content in ASP. NET. To achieve amazing paging simplicity, just a few lines of code can be done.

Data paging in ASP
There are many ways to implement data paging in ASP. One of the most common methods is to implement data paging through the attributes of ADO RecordSet. However, even if these attributes are used, designers still need to write a lot of code. Of course, there are other ways to achieve data paging, such as using stored procedures and client scripts. All these methods require the designer to write too much code, and the ASP code and HTML code are mixed together, so the maintenance and design are troublesome.

Data paging in ASP. NET
Fortunately, the implementation of data paging in ASP. NET is much simpler and clearer than that in ASP. Of course, there are not so many code to write. Here, we use the DataGrid to implement data paging, because the DataGrid Control can process data paging by itself, so we really need to write little code. First, let's look at a DataGrid, which obtains the specific data in the database by bundling DataSet.
In the following code, you can see that there are very few HTML parts, even if you can include a DataGrid Control. We have set some DataGrid attributes to enhance the appearance of the DataGrid. Of course, you can also set these attributes to enhance the appearance. You can simply use the control by default. <Html>
<Body>
<Asp: datagrid id = "dgPopularFAQs" runat = "server" BorderWidth = "0"
CellPadding = "2" Width = "100%"
Font-Name = "Verdana"
Font-Size = "Smaller"

HeaderStyle-HorizontalAlign = "Center"
HeaderStyle-Font-Bold = "True"
HeaderStyle-BackColor = "Navy"
HeaderStyle-ForeColor = "White"

AlternatingItemStyle-BackColor = "# dddddddd">
</Asp: datagrid>
</Body>
</Html>

Next, we need to write code to request data in the database, put the data into DataSet, and then bind the data to the DataGrid control. Here, the DataGrid Control is dgPopularFAQs. The code for connecting to the Database SQL Server 7 can be seen below. If you need to connect to other databases, you can change the SQL statements in the names of all the following instances to OleDB. For example, change Dim myDA as New SqlDataAdapter () to Dim myDA as New OleDbDataAdapter (). <% @ Import Namespace = "System. Data" %>
<% @ Import Namespace = "System. Data. SqlClient" %>
<Script language = "vb" runat = "server">
Sub Page_Load (sender as Object, e as EventArgs)
BindData ()
End Sub

Sub BindData ()
'1. Establish a connection
Dim myConnection as New SqlConnection (<I> ConnectionString </I>)

'2. Create a Command object
Const strSQL as String = "select faqid, Description, DateEntered, ViewCount "&_
"FROM tblFAQ order by faqid"
Dim myCommand as New SqlCommand (strSQL, myConnection)

3. Create a DataAdapter
Dim myDA as New SqlDataAdapter ()
MyDA. SelectCommand = myCommand

'4. Component DataSet
Dim myDS as New DataSet ()
MyDA. Fill (myDS)

'5. Bind data
DgPopularFAQs. DataSource = myDS
DgPopularFAQs. DataBind ()
End Sub
</Script>

Below is the running effect of the above Code (figure 1)

Note that the ConnectionString in the above Code must be a valid SQL database connection statement. For example, database connections in the following format (there are some minor changes when using OleDb ):
Server = IPAddress; uid = userName; pwd = password; database = databaseName
The preceding database connection and data display are implemented in the following five steps:
1. Connect to the database;
2. Create a Command object using an appropriate SQL query statement;
3. Create a DataAdapter;
4. Create a DataSet based on the data obtained from the request;
5. Bind DataSet to the DataGrid;
We noticed that the DataGrid Control can easily display data in the database with good styles. Taking a closer look at the program running result, we found that the appearance style of the DataGrid control is very good, and the implementation of this effect does not have to be like ASP code and HTML code in ASP.
All the data in the database is displayed using the DataGrid Control. The following page displays the data.

Data paging implementation
To use the DataGrid to implement data paging, you only need to perform the following steps:
1. Set the DataGrid Control's AllowPaging to True, which is to set the DataGrid to allow pagination;
2. Write the OnPageIndexChanged event to process paging requests;
In this way, we can set the corresponding properties and related events for the DataGrid in the code above to implement data paging: <asp: datagrid id = "dgPopularFAQs" runat = "server" BorderWidth = "0"
CellPadding = "2" Width = "100%"
Font-Name = "Verdana"
Font-Size = "Smaller"
AutoGenerateColumns = "False"

HeaderStyle-HorizontalAlign = "Center"
HeaderStyle-Font-Bold = "True"
HeaderStyle-BackColor = "Navy"
HeaderStyle-ForeColor = "White"

AlternatingItemStyle-BackColor = "# dddddddd"

AllowPaging = "True"
PageSize = "15"
OnPageIndexChanged = "dgPopularFAQs_Paged">
</Asp: datagrid>

In the above Code, we need to note that there is another attribute, that is, PageSize. This attribute sets the number of data entries displayed on each page after pagination. Here, 15 entries are displayed on each page. If this attribute is not defined, 10 entries are displayed by default. Now, we only need to define data paging events. Of course, this is also relatively simple: when you click a new page number, change the current page number CurrentPageIndex to the new page number. The following is the page change event code: <script language = "vb" runat = "server">
Sub dgPopularFAQs_Paged (sender as Object, e as DataGridPageChangedEventArgs)
DgPopularFAQs. CurrentPageIndex = e. NewPageIndex
BindData ()
End Sub
</Script>

Note that when the page changes, we need to re-bind the data. In a similar situation, we need to bind data when posting the page for the first time, and do not bind the data after refresh again: <script language = "vb" runat = "server">
Sub Page_Load (sender as Object, e as EventArgs)
If Not Page. IsPostBack then
BindData ()
End If
End Sub
</Script>

Now let's look at a program running instance:

We can see that the above program has been based on 15 records per page, but if you follow the above method design, the results can be paged, but not the above effect. Why? Because we have added some enhancement effects, which are defined by PagerStyle, for example, the following code: <asp: datagrid...>
<PagerStyle Mode = "<I> Mode </I>"
NextPageText = "<I> NextPageText </I>" PrevPageText = "<I> PrevPageText </I>"
Position = "<I> PagePosition </I>">
</PagerStyle>
</Asp: datagrid>

In the above Code, the Mode (page Mode) can be set to NextPrev or NumericPages. NextPrev is also the "Previous Page" method. NumericPages is a number; Position (page Position) it can be set to Top, Bottom, or TopAndBottom.

You should know
The above implementation of paging is very simple, but we still need to really understand paging. Each time a user clicks a new page, the entire DataSet needs to be re-built. If the data volume of this DataSet is not large, there is certainly no problem, but if there is a DataSet with 1000 pieces of data, every time a page is changed in a request, it is not ideal to implement paging in this way. At this time, we can no longer use the above method to implement paging, we can use the DataGrid AllowCustomPaging to implement.

AllowCustomPaging of the DataGrid
In fact, the paging method we mentioned above is only applicable when the data volume is small. Many articles on the Internet introduce data paging and only mention the above method. When there is a large amount of data, the above method will consume a lot of resources, so we must seek other solutions, it is best, every time you change the page, load the page data that needs to be displayed to the memory, instead of all the page data.
The AllowCustomPaging attribute of the DataGrid can implement the above functions. First, set the AllPaging and AllowCustomPaging attributes of the DataGrid to True, and then set the PageIndexChanged event.
In the PageIndexChanged event, we first set the CurrentPageIndex attribute to the page number to be displayed. Then, we construct a DataSource with only one page data and bind the data to the DataGrid.
When AllowCustomPaging is set to False, the DataGrid assumes that all DataSource data is required to be displayed. The DataGrid determines the data to be displayed based on CurrentPageIndex and PageSize. In fact, it only selects a part of all data for display, the undisplayed data is still in the memory. In addition, the DataGrid recalculates the page data to be displayed every time the page is changed.
When AllowCustomPaging is set to True, the DataGrid determines the data to be displayed based on the VirtualItemCount and PageSize attributes. Each time the page is changed, only the data to be displayed is loaded.
Now, let's look at a specific example: <% @ Import Namespace = "System. Data" %>

<Html>
<Script language = "VB" runat = "server">

Dim start_index As Integer

Function CreateDataSource () As ICollection

Dim dt As New DataTable ()
Dim dr As DataRow

Dt. Columns. Add (New DataColumn ("IntegerValue", GetType (Int32 )))
Dt. Columns. Add (New DataColumn ("StringValue", GetType (String )))
Dt. Columns. Add (New DataColumn ("CurrencyValue", GetType (Double )))

Dim I As Integer
For I = start_index To (start_index + ItemsGrid. PageSize)-1
Dr = dt. NewRow ()

Dr (0) = I
Dr (1) = "Item" + I. ToString ()
Dr (2) = 1.23 * (I + 1)

Dt. Rows. Add (dr)
Next I

Dim dv As New DataView (dt)
Return dv
End Function 'createdatasource

Sub Page_Load (sender As Object, e As EventArgs)

If CheckBox1.Checked Then
ItemsGrid. PagerStyle. Mode = PagerMode. NumericPages
Else
ItemsGrid. PagerStyle. Mode = PagerMode. NextPrev
End If
If Not IsPostBack Then
Start_index = 0
ItemsGrid. VirtualItemCount = 100
End If

BindGrid ()
End Sub 'page _ Load

Sub Grid_Change (sender As Object, e As DataGridPageChangedEventArgs)

ItemsGrid. CurrentPageIndex = e. NewPageIndex
Start_index = ItemsGrid. CurrentPageIndex * ItemsGrid. PageSize
BindGrid ()
End Sub 'grid _ Change

Sub BindGrid ()

ItemsGrid. DataSource = CreateDataSource ()
ItemsGrid. DataBind ()
End Sub 'bindgrid
</Script>

<Body>

<Form runat = server>

<H3> DataGrid Custom Paging Example

<Asp: DataGrid id = "ItemsGrid" runat = "server"
BorderColor = "black"
BorderWidth = "1"
CellPadding = "3"
AllowPaging = "true"
AllowCustomPaging = "true"
AutoGenerateColumns = "false"
OnPageIndexChanged = "Grid_Change">

<PagerStyle NextPageText = "Forward"
PrevPageText = "Back"
Position = "Bottom"
PageButtonCount = "5"
BackColor = "#00 aaaa">
</PagerStyle>

<AlternatingItemStyle BackColor = "yellow">
</AlternatingItemStyle>

<HeaderStyle BackColor = "#00 aaaa">
</HeaderStyle>

<Columns>

<Asp: BoundColumn HeaderText = "Number"
DataField = "IntegerValue"/>

<Asp: BoundColumn
HeaderText = "Item"
DataField = "StringValue"/>

<Asp: BoundColumn
HeaderText = "Price"
DataField = "CurrencyValue"
DataFormatString = "{0: c}">

<ItemStyle HorizontalAlign = "right">
</ItemStyle>

</Asp: BoundColumn>

</Columns>

</Asp: DataGrid>

<Br>

<Asp: CheckBox id = "CheckBox1"
Text = "Show page navigation"
AutoPostBack = "true"
Runat = "server"/>

</Form>

</Body>
</Html>

The above program runs as follows:

Summary:
Generally, we directly use the first method for data paging. If the data volume is large or sensitive to resource consumption, the second method is better.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.