Search code examples
c#asp.netsortinggridviewtemplatefield

GridView Sorting expression on a Text Field


I have following field in a grid view:

<asp:TemplateField HeaderText="Status">
    <ItemTemplate>
       <asp:Label ID="Label3" runat="server" Text='<%#Eval("JobEstimation").ToString() == "1" ? "Yes" : "No" %>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>

Now how do I enable sorting in this filed? "SortExpression="???"".

So when the user click the sort it should sort base on alphabet order.


Solution

  • As stated in comments, it would be better to implement that conversion within the Database, but pertinent to you question, the answer would depend on the actual content of that field. As a simple solution, you may try the following code snippet:

    <asp:TemplateField HeaderText="Job Est" SortExpression="JobEstimation">
       <ItemTemplate>....</ItemTemplate>
    </asp:TemplateField>
    

    Alternatively, you may add the Command/Link Button to the HeaderTemplate:

    <asp:TemplateField SortExpression="JobEstimation">
        <HeaderTemplate>
            <asp:LinkButton ID="sortJobEst" runat="server" Text="Job Est" CommandName="Sort" CommandArgument="JobEst" />
        </HeaderTemplate>
    </asp:TemplateField>
    

    and hook it to the GridView RowCommand event (re: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand(v=vs.110).aspx):

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Sort"))
        {
            // add your code to sort
            e.CommandArgument.ToString()...
            BindGridView();
        }
    }
    

    Hope this may help.