Hi, You see a lot of codes in which you came know that how to sort the GridView Contents. In this example you will see that how to display the appropriate image of sorting while applying the sorting. Following are the steps you have to follow to achieve the functionality.
Step 1 Drag and Drop an GridView Control from the data section of toolbox and give it the appropriate name. For this Example I use the gvSort.
Step 2 Make the template columns for the gvSort
<asp:datagrid id="gvSort" runat="server" Width="100%" GridLines="Horizontal" AutoGenerateColumns="False" AllowSorting="True"> <Columns> <asp:TemplateColumn SortExpression="Text"> <HeaderTemplate> <table width="125px" height="25px"> <tr> <td> <asp:LinkButton ID="lbSort" Runat="server" CommandArgument="Text" CommandName="Sort">UserName</asp:LinkButton> </td> <td> <img id="imgSort" runat="server" style="visibility:hidden"> </td> </tr> </table> </HeaderTemplate> <ItemTemplate> <TABLE> <TR> <TD> <asp:Label id="lblName" Runat="server"> <%# DataBinder.Eval(Container.DataItem, "Name")%> </asp:Label> </TD> </TR> </TABLE> </ItemTemplate> </asp:TemplateColumn> </asp:datagrid> <INPUT id="hdTextSort" type="hidden" value=" DESC" name="hdTextSort" runat="server">
Step 3 Now, you have to trigger the GridView Sort event
Private Sub gvSort_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles gvSort.SortCommand Me.LoadGrid(dtUsers)'Function to load the Gridview Dim dv As DataView = New DataView(dtUsers) Dim strSort As String = "" Me.hdImgText.Value = e.SortExpression If e.SortExpression.ToString().ToLower() = "text" Then strSort = e.SortExpression & Me.hdTextSort.Value If Me.hdTextSort.Value = " ASC" Then Me.hdTextSort.Value = " DESC" ElseIf Me.hdTextSort.Value = " DESC" Then Me.hdTextSort.Value = " ASC" End If End If dv.Sort = strSort Me.gvSort.DataSource = dv Me.gvSort.DataBind() End Sub
Private Sub LoadGrid(ByRef dtUsers As DataTable) 'Code to fill Get the users from Database and then bind the datatable to GridView End Sub
Step 4 Now, you have to trigger the GridView ItemDatabound event
If e.Item.ItemType = ListItemType.Header Then If Me.hdClicked.Value = "clicked" Then Dim imgText As HtmlImage imgText = e.Item.FindControl("imgSort") If Me.hdImgText.Value.ToLower() = "text" Then imgText.Style.Add("visibility", "visible") If Me.hdTextSort.Value.ToLower() = " asc" Then imgText.Src = "images\AddDown.png" ElseIf Me.hdTextSort.Value.ToLower() = " desc" Then imgText.Src = "images\AddUp.png" End If End IF End IF End IF
|
No responses found. Be the first to respond and make money from revenue sharing program.
|