Sort gridView by proper column which is TemplateField

Jaro picture Jaro · Oct 5, 2011 · Viewed 10.2k times · Source

I have got problem with sorting column in gridView. I want to select only those rows in column which name equal for example "Finished"

My gridView consists of few BoundField and TamplateFields. When I want to sort by proper BoundField I put proper string to property FilterExpression. For example:

Field in GridView: <asp:BoundField DataField="identifier" HeaderText="Case number" SortExpression="identifier" />

so I set FilterExpression = "[identifier] LIKE '%" + txtCaseNumber.Text + "%'"

where identifier is DataField in BoundField and In this case everything is ok. But when I want to select proper rows from column wihich name equal Fininish from TempateField I don't know how I should do it. Exaple of TemplateField looks like this:

<asp:TemplateField HeaderText="Status" SortExpression="Status">
                    <ItemTemplate>
                        <asp:Label ID="lblStatus" runat="server" Text='<%# Utils.ConvertToProcessStatus((int)Eval("status"))%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>

If anyone know how I can do it??

Thanks for help.


It's ok but I forgot mention that I have my own user contron (ucCaseFilter) which consists of DropDownList from which I choose status. For example: Failed, InProgress, Finish ... Inside this control I create public property Filter and I want to assign string value which will be select proper column and sort them .

Filter = "[???] = '" + ddlCaseStatus.SelectedValue + "'"; 

Then in gridView use it:

FilterExpression = ucCaseFilter.Filter;

I don't know how get column name or other approach which afford me sort by "Status" column.

If I didn't understand previous answerd and it refer to correct soluti

Answer

Waqas picture Waqas · Oct 5, 2011

Change your <asp:TempleteField /> to add <HeaderTemplate /> markup with a LinkButton like this:

<asp:TemplateField SortExpression="Status">
    <HeaderTemplate>
        <asp:LinkButton ID="lnkSort" runat="server" Text="Status" CommandName="Sort" CommandArgument="Status" />                
    </HeaderTemplate>
</asp:TemplateField>

and in grd_RowCommand event handle "Sort" command and use the CommandArgument to build your filter string

protected void grd_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName.Equals("Sort"))
    {
        FilterExpression = e.CommandArgument.ToString() + " LIKE '%" + txtCaseNumber.Text + "%'";
        BindGridView();
    }   
}