Some time ago I made the first ASP. NET project, which is very simple. When a small problem occurs during the DataGrid paging, let's refer to the msdn example. In the actual process, it seems that there is a problem, and the improvement is as follows:
Link: ms-help: // MS. MSDNQTR.2003FEB. 2052/vbcon/html/vbwlk1_throughdisplayingdatainlistboxesonwebformspage.htm
Note: This article uses two SQL statements to use different statements when turning pages forward or backward. After improvement, you can use only one statement. The stored procedure is used in the project:
Create procedure selectAllUser
(
@ Id int
)
AS
Select top 15 Id, UserName, IDcard, Sex, Birthday, MailAddr, GetscholarTime
From UserInfo
Where Id> = @ Id
GO
The key code is as follows:
///
/// Read 15 records starting with userID from the database and display
///
///Private void showAllUser (int userID)
{
ManageDB managedb = new ManageDB ();
Int count = managedb. getUserCount (); // This method gets the total number of records
If (count =-1)
{
Response. Redirect ("error. aspx", true );
Return;
}
Count = count/this. gridUser. PageSize;
SqlDataReader reader = managedb. getAllUser (userID );
This. gridUser. DataSource = reader;
This. gridUser. DataBind ();
Reader. Close ();
ViewState ["CurrentPage"] = CurrentPage;
ViewState [CurrentPage. ToString ()] = this. gridUser. Items [0]. Cells [0]. Text;
If (CurrentPage <= 0)
{
This. btnPrevious. Enabled = false;
}
If (CurrentPage> = count)
{
This. btnNext. Enabled = false;
}
}
Next page button click event:
Private void btnNext_Click (object sender, System. EventArgs e)
{
This. btnPrevious. Enabled = true;
CurrentPage = (int) (ViewState ["CurrentPage"]);
CurrentPage ++;
// The following code has a + 1 operation, which is required to ensure that no duplicate records are obtained.
Int lastID = Convert. ToInt32 (this. gridUser. Items [this. gridUser. PageSize-1]. Cells [0]. Text) + 1;
This. showAllUser (lastID );
}
Click Event on the previous page
Private void btnprevius_click (object sender, System. EventArgs e)
{
This. btnNext. Enabled = true;
CurrentPage = Convert. ToInt32 (ViewState ["CurrentPage"]);
CurrentPage --;
If (CurrentPage> = 0)
{
Int firstid;
Firstid = Convert. ToInt32 (ViewState [(CurrentPage). ToString ()]);
This. showAllUser (firstid );
}
}
Finally, add the following content in the page load event:
If (! Page. IsPostBack)
{
CurrentPage = 0;
This. showAllUser (0 );
}
In this way, a simple page is improved. Of course, we can also display the total number of pages, the current number of pages. However, this paging function is not powerful, so you cannot directly jump to the page number. However, the paging efficiency is quite high.
The entire source code can be downloaded here. Note that the database is SQL server2000.
In addition, my Blog will launch. net books and source code downloads recently. Please stay tuned!