排序自定义gridview ASC和DESC

时间:2015-09-01 01:29:40

标签: c# asp.net sorting gridview

我有自定义gridview。代码如下。

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  GridLines="None" Width="768px" CellPadding="4" ForeColor="#333333" AllowPaging="True" PageSize="20" OnPageIndexChanging="gridView_PageIndexChanging" AllowSorting="true" OnSorting="gridViewSorting">
    <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:TemplateField HeaderText="User ID" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="33%" SortExpression="USERID" > 
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButton1" OnClick="LinkButton1_Click" Text='<%#Eval("USERID") %>' runat="server"> 
                    <asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>    
            <asp:BoundField DataField="USERNAME" HeaderText="User Name" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="33%">  
            </asp:BoundField>
            <asp:BoundField DataField="USERPOSITION" HeaderText="User Position" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="33%"> 
            </asp:BoundField>
        </Columns>
    <PagerSettings  Mode="Numeric" PageButtonCount="10"/>
    <PagerStyle HorizontalAlign="Center" BackColor="White" />
</asp:GridView>

我希望在此gridview中进行排序,但由于它是模板字段和数据字段,因此我无法使用asp.net中的默认函数

我使用后端代码进行排序,但似乎无效。

用于排序的后端代码如下

protected void gridViewSorting(object sender, GridViewSortEventArgs e)
{
    DataTable dataTable = GridView1.DataSource as DataTable;

    if (dataTable != null)
    {
         DataView dataView = new DataView(dataTable);
         dataView.Sort = e.SortExpression + "USERID ASC"; 
         GridView1.DataSource = dataView;
         GridView1.DataBind();
    }
}

我尝试了几种方法,并参考了一些资源,它仍在工作

您的评论和建议非常感谢!!

非常感谢你!

1 个答案:

答案 0 :(得分:0)

如果您只想按UserID排序,可以从sortexpression中删除它,只需附加排序方向。

dataView.Sort = e.SortExpression + " ASC";