asp.net vb.net gridview - 无法排序!

时间:2009-10-02 15:18:43

标签: asp.net vb.net gridview sorting

我尝试将此gridview排序,但它根本不起作用,任何人都知道为什么?

    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()

令人沮丧!

2 个答案:

答案 0 :(得分:2)

我认为您没有在中分配 SortExpression 属性。 有关更多详细信息,请查看this示例。

在您的示例中,只需添加

即可
.SortExpression= col.ColumnName

以下

 .DataField = col.ColumnName

答案 1 :(得分:1)

由于您要手动添加列,因此必须为每个列设置SortExpression属性。请参阅最后一点here