Ordinare le righe di un Datagrid in base ad una colonna
<%@ Page Language="vb" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<html>
<head>
<SCRIPT RUNAT="SERVER" language="vb">
Sub OrdinaPerCampo (sender As Object, e As DataGridSortCommandEventArgs)
ViewState("campo") = e.SortExpression
If ViewState("direzione") Is Nothing OrElse ViewState("direzione") = "DESC" Then
ViewState.Add("direzione", "ASC")
Else
ViewState("direzione") = "DESC"
End If
LoadDatabase()
End Sub
Sub LoadDatabase()
Dim dbConn As OleDbConnection
Dim myAdapter As OleDbDataAdapter
Dim sqlCmd As String
Dim strConn As String
Dim oDataSet As New DataSet
strConn = ""
strConn = strConn & "Provider=Microsoft.Jet.OLEDB.4.0;"
strConn = strConn & "Data Source=" & Server.MapPath("database/utenti.mdb") & ";"
strConn = strConn & "Persist Security Info=False"
sqlCmd = ""
sqlCmd = sqlCmd & "SELECT "
sqlCmd = sqlCmd & " nome, "
sqlCmd = sqlCmd & " cognome, "
sqlCmd = sqlCmd & " email "
sqlCmd = sqlCmd & " FROM utenti"
If Not ViewState("direzione") Is Nothing Then
sqlCmd += " ORDER BY " & ViewState("campo") & " " & ViewState("direzione")
End If
dbConn = New OleDbConnection(strConn)
Try
myAdapter = New OleDbDataAdapter(sqlCmd, dbConn)
myAdapter.Fill(oDataSet, "utenti")
MyDataGrid.DataSource = oDataSet.Tables(0).DefaultView
MyDataGrid.DataBind()
Finally
dbConn.Close()
End Try
End Sub
Sub Page_Load()
If Not Page.IsPostBack then
LoadDatabase()
End If
End Sub
</SCRIPT>
</head>
<body>
<form runat="server" ID="Form1">
<asp:DataGrid id="MyDataGrid" runat="server" AutoGenerateColumns="False" AllowSorting="True" OnSortCommand="OrdinaPerCampo">
<Columns>
<asp:BoundColumn DataField="nome" SortExpression="nome" HeaderText="nome" />
<asp:BoundColumn DataField="cognome" SortExpression="cognome" HeaderText="cognome" />
<asp:BoundColumn DataField="email" SortExpression="email" HeaderText="email" />
</Columns>
</asp:DataGrid>
</form>
</body>
</html>