ASP 101 - Active Server Pages 101 db_sort.aspx
<%@ Page Language="VB" %>
<%@ Import Namespace = "System.Data" %>
<%@ Import Namespace = "System.Data.SQLClient" %>
<script language="VB" runat="server">
	Sub Page_Load(sender As Object, e As EventArgs)
		Dim strSortField As String ' Field to sort by
		Dim strSortOrder As String ' "ASC" or "DESC"
		' Retrieve sorting parameters:
		' Get the field name and make sure the input is one of our field names.
		strSortField = Request.QueryString("field")
		Select Case LCase(strSortField)
			Case "last_name", "first_name", "sales"
				strSortField = strSortField
			Case Else
				strSortField = "id"
		End Select
		' Check for descending o/w we default to ascending
		Select Case LCase(Request.QueryString("order"))
			Case "desc"
				strSortOrder = "DESC"
			Case Else
				strSortOrder = "ASC"
		End Select
		BindDataToGrid(strSortField, strSortOrder)
	End Sub
	Sub BindDataToGrid(strSortField As String, strSortOrder As String)
		Dim myConnection  As SqlConnection 
		Dim myDataAdapter As SqlDataAdapter
		Dim myDataSet     As DataSet
		Dim strSQL        As String
		myConnection = New SQLConnection("Data Source=10.2.2.133;" _
					& "Initial Catalog=samples;User Id=samples;Password=password;" _
					& "Connect Timeout=15;Network Library=dbmssocn;")
		strSQL = "SELECT * FROM [sample] ORDER BY [" & strSortField & "] " & strSortOrder & ";"
		myDataAdapter = New SqlDataAdapter(strSQL, myConnection)
		myDataSet = new Dataset()
		myDataAdapter.Fill(myDataSet, "sample")
		DBSortDataGrid.DataSource = myDataSet
		DBSortDataGrid.Databind()
	End Sub
</script>
<html>
<head>
<title>ASP.NET Database Sort Sample</title>
</head>
<body>
<form runat="server" EnableViewState="false">
<asp:DataGrid id="DBSortDataGrid" runat="server" 
	Border      = 1
	CellSpacing = 1
	HeaderStyle-BackColor = "#CCCCCC"
	HeaderStyle-ForeColor = "#000000"
	HeaderStyle-Font-Bold = "True"
	ItemStyle-BackColor   = "#FFFFFF"
	AlternatingItemStyle-BackColor = "#CCCCFF"
	AutoGenerateColumns = "False"
	>
	<Columns>
		<asp:BoundColumn DataField="id"         HeaderText="id (<a href='?field=id&order=asc'>+</a> / <a href='?field=id&order=desc'>-</a>)" />
		<asp:BoundColumn DataField="last_name"  HeaderText="last_name (<a href='?field=last_name&order=asc'>+</a> / <a href='?field=last_name&order=desc'>-</a>)" />
		<asp:BoundColumn DataField="first_name" HeaderText="first_name (<a href='?field=first_name&order=asc'>+</a> / <a href='?field=first_name&order=desc'>-</a>)" />
		<asp:BoundColumn DataField="sales"      HeaderText="sales (<a href='?field=sales&order=asc'>+</a> / <a href='?field=sales&order=desc'>-</a>)" />
	</Columns>
</asp:DataGrid>
</form>
<hr />
<p>
Click <a href="http://www.asp101.com/samples/db_sort_aspx.asp">here</a>
to read about and download the source code.
</p>
</body>
</html>