Tuesday, 29 November 2011

LET USERS SORT YOUR DISPLAYED RECORDS

It's one thing to list your records in ascending or descending order on your web page, but how about letting the user sort your records the way they want? Let's say you are displaying a list of users on your page and you want to display all of the first and last names.

The first thing you need to do is create a database called MyData. Then create a table called tblUsers with these fields:
ID - autonumber
FirstName - text field
LastName - text field

Then, start adding some names to your database.

Next, you create a page called usersort.asp and copy the below code into your page:



First Name ASC sort DESC

Last Name ASC sort DESC


<% DIM strOrderBy, tmpOrderBy strOrderBy = Request.QueryString("OB") Select Case strOrderBy Case "f_a" tmpOrderBy = "ORDER BY FirstName ASC" Case "fn_d" tmpOrderBy = "ORDER BY FirstName DESC" Case "l_a" tmpOrderBy = "ORDER BY LastName ASC" Case "l_d" tmpOrderBy = "ORDER BY LastName DESC" Case Else tmpOrderBy = "ORDER BY FirstName DESC" End Select DIM mySQL, objRS mySQL = "Select FirstName, LastName FROM tblUsers " & tmpOrderBy Set objRS = Server.CreateObject("ADODB.Recordset") objRS.Open mySQL, objConn DO WHILE NOT objRS.EOF %>

<%=objRS("FirstName")%> <%=objRS("LastName")%>


<% objRS.MoveNext Loop objRS.Close Set objRS = Nothing objConn.Close Set objConn = Nothing %>

This will display all of the users in your database in descending order by first name as the default. Then, when the user clicks on either ASC or DESC next to First Name or Last Name, they will be able to change the sort order the way they want. Enjoy!

http://www.aspwebpro.com/aspscripts/database/usersort.asp

No comments:

Post a Comment