首页 > 开发 > 综合 > 正文

关于数据分页(转自www.codeproject.com)

2024-07-21 02:22:35
字体:
来源:转载
供稿:网友

商业源码热门下载www.html.org.cn

first of all, let me say a few words about this article. this is not an entirely original article but an asp.net adaptation of the asp article that i’ve posted a few months ago. original article can be found here: ado recordset paging in asp.

the purpose of this article is to show how to implement data paging with ado.net. it is not a generic asp.net or even ado.net tutorial. the article looks at the very specific case when you need a better control over your own custom presentation of data and of navigation provided to your users. this is why you will not see any webforms or webcontrols here. i did not use new datagrid control even though it comes with the data paging capabilities. datagrid control is very powerful and has a lot of useful features, but it is somewhat limiting in the way of presentation of data and page navigation links. beside that, there are plenty of samples and articles on how to use new asp.net capabilities written by other people.

every once in a while i come across the task of displaying a large number of records on the web. the good example is displaying the results of a search. most of the time i do not know the number of records that i have to display in advance. in addition to this, as the usage of the application growth the size of the database will grow accordingly. that leaves me as well as anyone with the similar application requirements no other choice, but to develop some kind of algorithm to display records in the smaller chunks - pages.


everyone is familiar with the way search results are displayed by internet search engines. you get the first page of results that are limited to some number of records (20 for example) and some navigational links to go to the first, previous, next or the last page. some sites give you the ability to go directly to specific page number, some use a mixture of both.

so how does one implements data paging mechanism with asp.net? specifically, how do we implement record paging using ado.net?

let’s pretend that we have a database with the table called tblitem that is used to store information about our items (whatever they are?). let me also imagine that one of the fields in tblitem called itemname. we are given a task of creating a set of pages to give a user an ability to search for the items by the itemname field. we decided to make a set of two pages. one page will display the search form and one for the results of the search.

please excuse me, but i will skip all the variable declarations and html formatting.

first page should be easy. it’s a standard html form that could look something similar to this:

...
<form action="results.asp" method="get">
item name: <input type="text" name="keyword"> <input type="submit" value=" find ">
</form>
...

second page is where all the magic should happen. this is what the second page (results.aspx) should be able to do:
1. receive the keyword that user have entered.
2. search the database for records containing keyword.
3. display a page of resulting records.
4. provide user with some navigation links to display more pages of results if needed.


1. receive keyword
receiving the keyword is as easy as:

keyword = request.querystring("keyword").trim()

2. search the database and retrieve data.
now we have everything we need to get an ado.net dataset with the items that contain our keyword in their itemname.

first we create a sql statement that will do the search:

sql = "select * from tblitem where itemname like '%" & keyword.replace("'", "''") & "%'"

notice that i’ve used replace function to double single quotes in the search string. without it if user enters a single quote in his/her keyword you will receive an error.

let's try to open a database connection and get the data:

    try
        odconn = new oledbconnection(strconn)
        odadapt = new oledbdataadapter(sql, odconn)
        ds = new dataset
        odadapt.fill(ds)
        
        ' get our datatable
        dt = ds.tables(0)

        ' get record count
        nreccount = dt.rows.count

    catch e as exception
        response.write("error: <b>" & e.message & "</b><p>")
        nreccount = 0
    end try

this is what’s going on in the above lines of code: first we construct new oledbconnection object using our connection string. we create oledbdataadapter next providing our sql statement and reference to the connection object. after creating new dataset object we instruct our dataadapter to populate (fill) dataset with the data out of our database. then we get a reference to the first table in the dataset that represents our data and retrieve the number of records (rows) returned in that table. try and catch are obviously there to try and catch any errors during these database operations.

4. navigation links
yes it is a fourth step. i did leave the third step (displaying of the results) for the last because in order for us to display the records we need to figure some things out. i also think it is better to create and display navigation links on the top of the page before the results.

at this point we have to figure out couple of things: do we have any results from our search and if so how many pages of results do we have?

presence of the results is easily determent by checking record count (notice we do not have eof property anymore):


if nreccount = 0 then
    ... ' clean up
    ... ' do the no results html here
    response.write("no items found.")
    response.end
    ... ' done
end if

the number of pages we have is obviously depends on the number of items we want to display per page. ado.net does not have all those cool properties that we’ve come to like and use in ado. pagesize, pagecount, absolutepage properties of ado recordset object are not available to us anymore. we will have to resort to some very simple calculations in order to determent number of pages of data we have at hand.

npagecount = nreccount / records_per_page
if nreccount mod records_per_page > 0 then
    npagecount += 1
end if

now we need to talk about the current page number. since we want this page (results.aspx) to be able to display any one of the pages of results we have to have a way to specify which page will the user see right now. we will do it by passing an additional parameter to our results.aspx script that we will call "page". so the link to our page could look like this:

http://..../results.aspx?keyword=blahblahblah&page=3

with that said we can figure out the number of the page that is requested by the user by simple checking page parameter:

npage = convert.toint32(request.querystring("page"))

we need to make sure that the number of page requested by user is within the acceptable range and fix it if needed:

if npage < 1 or npage > npagecount then
    npage = 1
end if

now we can create our navigation links by simply linking to this page with the same value for keyword and the specific page number. for example:

' first page
response.write("<a href=""results.aspx?keyword=" & keyword & "&page=1"">first page</a>")
' previous page
response.write("<a href=""results.aspx?keyword=" & keyword & "&page=" & (npage - 1).tostring() & """>prev. page</a>")
' next page
response.write("<a href=""results.aspx?keyword=" & keyword & "&page=" & (npage + 1).tostring() & """>next page</a>")
' last page
response.write("<a href=""results.aspx?keyword=" & keyword & "&page=" & npagecount.tostring() & """>last page</a>"
' 15th page
response.write("<a href=""results.aspx?keyword=" & keyword & "&page=15"">15th page</a>")

there is an alternative way of providing navigational links provided in my sample script.

3. display a page of results
all we have left to do is to display a page of results.

before we do that though we need to find out what are the indexes of the starting and ending rows (records) of this page are:

nstart = records_per_page * (npage - 1)
nend = nstart + records_per_page - 1
if nend > nreccount - 1 then
    nend = nreccount - 1
end if

now we are ready to output a page of records. in contrast to ado, with ado.net we should not use while loop. we already know the indexes of records we want to show, so for loop will work just great:

for i = nstart to nend
    response.write(dt.rows(i)("itemname") & "<br>")
next

that is it. sample that i have included here is a bit more complex, because i've combined both html search form and displaying of the results in one page. that is why there is an additional mode parameter being used in every link. all the code concerning displaying of the results of the search is in the showresults() function.

  
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表