views:

378

answers:

2

I try to make this gridview sortable, but it simply doesn't work, anyone know why?

 Dim sql As String = "SELECT Product_ID, Code, Trade_Name "
 sql = sql & "FROM Product "
 sql = sql & "WHERE Category = ? "
 Dim conn As String = WebConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
 Dim dad As New OleDbDataAdapter(sql, conn)
 dad.SelectCommand.Parameters.AddWithValue("?", CatID)
 Dim dtblProduct As New DataTable()
 dad.Fill(dtblProduct)

 Dim grdProducts As New GridView
 grdProducts.ID = "grdProducts"
 grdProducts.CellPadding = 5
 grdProducts.CellSpacing = 5
 grdProducts.GridLines = GridLines.None
 grdProducts.AutoGenerateColumns = False
 grdProducts.HeaderStyle.HorizontalAlign = HorizontalAlign.Left
 grdProducts.EmptyDataText = "No Products Available."
    grdProducts.DataSource = dtblProduct
 Dim dataNavigateUrlFields() As String = {"Product_ID"}

 Dim blnfirstCol As Boolean = True

 Dim strPageResolveURL As String = String.Empty
 Dim strLnkSelectText As String = String.Empty

 For Each col As Data.DataColumn In dtblProduct.Columns
  If blnfirstCol Then
     Dim lnkSelect As New HyperLinkField
     With lnkSelect
      .Text = _strAction
      .DataNavigateUrlFields = dataNavigateUrlFields
      .DataNavigateUrlFormatString = Page.ResolveUrl(_strDirectPage & ".aspx?ProductID={0}&Cat=" & CatID)
     End With
     grdProducts.Columns.Add(lnkSelect)
   blnfirstCol = False
  Else
   Dim myBoundField As New BoundField()
   With myBoundField
   Select Case col.ColumnName
    Case "CODE"
     .HeaderText = "Code"
     .ItemStyle.Width = 100
     .HtmlEncode = False
    Case "TRADE_NAME"
     .HeaderText = "Trade Name"
     .ItemStyle.Width = 200
   End Select
   .DataField = col.ColumnName
   .Visible = True
   End With
   grdProducts.Columns.Add(myBoundField)
  End If
    Next

 grdProducts.AllowSorting = True ' Should already be true, but this doesnt help
 grdProducts.DataBind()

It's frustrating!

+1  A: 

Since you are adding columns manually, you have to set the SortExpression property for each of them. See last note here.

najmeddine
+3  A: 

I think you are not assigning SortExpression property in Columns. Please check this example for more detail.

In your example, just add

.SortExpression= col.ColumnName

below

 .DataField = col.ColumnName
Mahin