Just copy and paste this code into a new blank page. Change the Database name, UID and password. It uses the Northwind database with SQL Server and save it as a ‘.aspx’ page.
<%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.SQLClient” %>
<html>
<head>
<title>ASPExpress.com – Column Sorting in the DataGrid</title>
<script runat=”server” language=”VB”>
Protected SQLStmt As String = “SELECT CompanyName, ContactName, ContactTitle, Phone, Fax FROM Customers”
Sub Page_Load(Source As Object, E As EventArgs)
If Not Page.IsPostBack Then
BindData()
End If
End Sub
Sub BindData()
Dim myDataSet As New DataSet
Dim myDataSetCommand As SQLDataAdapter
Dim ConString As String
ConString = “server=YourServerName;database=Northwind;uid=internet;pwd=;”
myDataSetCommand = New SQLDataAdapter(SQLStmt, ConString)
myDataSetCommand.Fill(myDataSet, “Customers”)
myDataGrid.DataSource = myDataSet.Tables(“Customers”).DefaultView
myDataGrid.DataBind()
End Sub
</script>
<script language=”VB” runat=”server”>
Sub SortCommand_OnClick(Source As Object, E As DataGridSortCommandEventArgs)
SQLStmt = SQLStmt & ” ORDER BY ” & E.SortExpression
BindData()
End Sub
</script>
</HEAD>
<BODY>
<form runat=”server” method=”post”>
<asp:Datagrid runat=”server”
Id=”MyDataGrid”
OnSortCommand = “SortCommand_OnClick”
AllowSorting = “True”
BorderColor=”black”
BorderWidth=”1″
GridLines=”Both”
CellPadding=”3″
CellSpacing=”0″
Headerstyle-BackColor=”#aaaadd”
Headerstyle-Forecolor=”#FFFFFF”
Headerstyle-Font-Name=”Arial”
Headerstyle-Font-Bold=”True”
Headerstyle-Font-Size=”11″
Font-Name=”Arial”
Font-Size=”10″
AlternatingItemStyle-BackColor=”#eeeeee”
AlternatingItemStyle-Font-Name=”Arial”
AlternatingItemStyle-Font-Size=”10″
/>
</form>
</BODY>
</HTML>