Home > database >  Click Header box to sort the column in Asp.net/C#/Vb.net
Click Header box to sort the column in Asp.net/C#/Vb.net

Time:06-15

Is there a way to sort the GridView (ASP.Net) by click anywhere in the header box? The current sort of the GridView is on the header text only. Tried searching but still no luck.

Thank you.

CodePudding user response:

Ok, there are a number of ways to do this. Even perhaps having buttons in place of link buttons.

but, this can work - use the riw data bound event, and for each header cell that has the link button, then you could add the same click even that the sort command uses.

So, say this:

Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound

    If e.Row.RowType = DataControlRowType.Header Then

        For Each MyHead As TableCell In e.Row.Cells
            For Each MyControl As Control In MyHead.Controls
                If MyControl.GetType.BaseType = GetType(LinkButton) Then
                    Dim btnLink As LinkButton = MyControl
                    MyHead.Attributes.Add("onclick", "__doPostBack(" & "'GridView1'" & ",'Sort$" & btnLink.Text & "')")
                End If
            Next
        Next

    End If
End Sub

The only part hard coded in above is GridView1 - you have to change that to the name you have for the Grid view, but the above does seem to work. In fact, the extra loop probably could be skipped, but if one column don't have sorting, then above check for the child controls as per above seems to be a good idea.

  • Related