문제

Here's the GridView:

<asp:GridView ID="MyGridView" runat="server" AllowPaging="true" AllowSorting="true"
    OnPageIndexChanging="MyGridView_PageIndexChanging"
    OnSorting="MyGridView_Sorting">
    <Columns>
        <asp:TemplateField HeaderText="ID" SortExpression="Id">
            <ItemTemplate>
                <asp:Label ID="idLabel" runat="server" Text='<%# Bind("Id") %>' />
            </ItemTemplate>
       </asp:TemplateField>
    </Columns>
</asp:GridView>

Here, the Id column is a string consisting always of the letter "T" followed by a number, i.e. "T1" or "T597" The other columns are fairly ordinary name and description String fields.

I need this Id column to sort as though the Id were numeric, ignoring the letter in front. But because it is there, it is being treated as a String and sorting as such: T1, T10, T100, T2, T231, T34, ...

So what I thought would be possible is:

protected void MyGridView_Sorting(object sender, GridViewSortEventArgs e)
{
    if (e.SortExpression.Equals("Id")
    {
         // Special sorting code
    }
    else
    {
        // Normal sorting code
    }
}

Where the "normal" sorting code follows the common pattern of converting the DataSource to DataView and setting DataView.Sort = e.SortExpression etc, for example: allow sorting by column gridview

So what do I do for the "special" sorting code?

UPDATE: Just to be clear, I have no trouble rolling my own function to compare two strings as I need. I do not, however, know how to apply that function to my Data Grid/ Data Source.

도움이 되었습니까?

해결책 2

The GridView allows DataKeyNames, and that is the solution here. When setting up the Data Source (in my case, a SQL query) include both the "FullId" and a "PlainId" which has stripped off the leading character and parsed the remainder as int. Use "FullId" as the column's text value, but make "PlainId" one of the DataKeyNames and use that as the SortExpression for the column.

다른 팁

You can implement the IComparer class for the DataGridView.Sort:

http://msdn.microsoft.com/en-us/library/wstxtkxs%28v=vs.85%29.aspx

You can separate the "T" and the following number in the Compare method.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top