0

我只是试图允许用户按它的任何列对 GridView 进行排序。

<asp:GridView ID="gvShows" runat="server" DataKeyNames="dataSource,title" Caption="Show List" AutoGenerateColumns="False" AllowSorting="True" AllowPaging="True" CaptionAlign="Left" OnSorting="gvShows_Sorting" >
                    <RowStyle BorderColor="Black" />
                    <Columns> 
                        <asp:TemplateField HeaderText="Select"> 
                            <ItemTemplate> 
                                <asp:CheckBox ID="cbSelect" runat="server" AutoPostBack="false"/> 
                            </ItemTemplate> 
                        </asp:TemplateField> 
                        <asp:BoundField HeaderText="Data Source" DataField="dataSource" /> 
                        <asp:BoundField HeaderText="Show ID" DataField="ShowId" /> 
                        <asp:BoundField HeaderText="Show Title" DataField="title" /> 
                        <asp:BoundField HeaderText="Episode Id" DataField="EpisodeID" /> 
                        <asp:BoundField HeaderText="Episode Title" DataField="EpisodeTitle" /> 
                        <asp:BoundField HeaderText="Genre" DataField="Genre" /> 
                        <asp:BoundField HeaderText="Show Type Description" DataField="ShowTypeDescription" /> 
                        <asp:BoundField HeaderText="Director Name" DataField="DirectorName" /> 
                        <asp:BoundField HeaderText="Release Year" DataField="ReleaseYear" /> 
                        <asp:BoundField HeaderText="Season Episode" DataField="SeasonEpisode" /> 
                    </Columns>  
                </asp:GridView>

    protected void gvShows_Sorting(object sender, GridViewSortEventArgs e)
    {
        var dataTable = Session["shows"] as DataTable;

        if (dataTable != null)
        {
            var dataView = new DataView(dataTable)
                {
                    Sort = e.SortExpression + " " + ConvertSortDirection(e.SortDirection)
                };

            gvShows.DataSource = dataView;
            gvShows.DataBind();
        }
    }

    private string ConvertSortDirection(SortDirection sortDirection)
    {
        string newSortDirection = String.Empty;

        switch (sortDirection)
        {
            case SortDirection.Ascending:
                newSortDirection = "ASC";
                break;

            case SortDirection.Descending:
                newSortDirection = "DESC";
                break;
        }

        return newSortDirection;
    }

当数据显示在 GridView 中时,我根本不允许单击标题文本以便对数据进行排序:

4

2 回答 2

5

您需要在您的 asp:BoundField 中添加“ SortExpression ”。

例如 :

<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
于 2013-06-18T09:48:16.500 回答
0

我知道了。我需要添加 SortExpressions 因为列不是自动生成的。

于 2013-06-18T17:27:50.280 回答