Hi,
I'm trying to allow sorting my gridview writing in the code behind page. My code for Bind the GridView is like this:
Private Sub BindMyGridView()
Dim DatabaseConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("MyServer").ConnectionString)
Dim adapter As SqlDataAdapter = New SqlDataAdapter
Dim selectSQL As String = "SELECT * FROM Clients WHERE id = @id"
Dim selectCMD As New SqlCommand(selectSQL, DatabaseConnection)
Dim id As Integer = firstGridView.SelectedValue
selectCMD.Parameters.Add(New SqlParameter("@id ", SqlDbType.Int))
selectCMD.Parameters("@id ").Value = id
adapter.SelectCommand = selectCMD
Dim dTable As DataTable = New DataTable
adapter.Fill(dTable)
MyGridView.DataSource = dTable
MyGridView.DataBind()
End Sub
And my code for sorting is like this:
Private Function SortDirectionSQL(ByVal direction As SortDirection) As String
Dim directionSQL As String = ""
Select Case direction
Case SortDirection.Ascending
directionSQL = "ASC"
Case SortDirection.Descending
directionSQL = "DESC"
End Select
Return directionSQL
End Function
Protected Sub MyGridView _OnSorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs)
Dim dTable As DataTable = MyGridView.DataSource
If dTable.Rows.Count > 0 Then
Dim dView As New DataView(dTable)
dView.Sort = e.SortExpression + " " + SortDirectionSQL(e.SortDirection)
MyGridView.DataSource = dView
BindMyGridView ()
End If
End Sub
However, the proble I'm having is in the line:
dTable.Rows.Count > 0
and this is happening becaus emy DataSource is always nothing.
Does anyone have ideas about how to solve this problem?
Thanks in advance.
Ana