如何在GridView中允许排序

本文关键字:排序 许排序 GridView | 更新日期: 2023-09-27 18:11:01

我有以下GirdView,它显示了一些文件的修改日期:

<asp:GridView ID="GridView1" AllowSorting="true" OnSorting="GridView1_Sorting" ClientIDMode="Static" runat="server" AutoGenerateColumns="false" EmptyDataText="No PDF was generated">
    <Columns>
        <asp:BoundField DataField="Text" HeaderText="File Name" SortExpression="FileName" />
        <asp:BoundField DataField="Value" HeaderText="File Date" SortExpression="FileDate" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="lnkDownload" Text="Download" runat="server" 
                    CommandArgument='<%# Container.DataItemIndex %>' 
                    OnClick="DownloadFile" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="lnkView" Text="View in Browser" 
                    CommandArgument='<%# Container.DataItemIndex %>' 
                    OnClientClick="window.document.forms[0].target='blank';" 
                    runat="server" OnClick="ViewFile" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

我正在用以下代码填充GridView:

if (!Page.IsPostBack)
    {
        BindData();
        //MessageBox.Show(files.Count() + ""); // displays the count for the files being displayed
    }
protected void BindData()
{
    try
    {
        filePaths = Directory.GetFiles(@"C:'PDFGenerate");
        files = new List<ListItem>();
        foreach (string filePath in filePaths)
        {
            files.Add(new ListItem(Path.GetFileName(filePath), File.GetLastWriteTime(filePath).ToString()));
        }
        GridView1.DataSource = files;
        GridView1.DataBind();
        Session["fileData"] = files;
    }
    catch (Exception ce)
    {
    }
    //MessageBox.Show(files.Count() + ""); // displays the count for the files being displayed
}

我允许在GridView中使用排序方法,并添加了排序表达式。我正试图编写c#代码,这将允许排序,但我不确定我将如何去做,因为我不使用SQL数据源:

protected void GridView1_Sorting(object server, GridViewSortEventArgs e)
    {
        switch (e.SortExpression)
        {
            case "FileName":
                if (e.SortDirection == SortDirection.Ascending)
                {
                    GridView1.DataSource = Session["fileData"];//DO BY ASCENDING
                    GridView1.DataBind();
                }
                else
                {
                    GridView1.DataSource = Session["fileData"];//DO BY DESCENDING
                    GridView1.DataBind();
                }
                break;
            case "FileDate":
                break;
        }
    }

更新:我是如何能够让它正确工作的…

protected void Page_Load(object sender, EventArgs e)
    {
        string strDirectory = @"C:'PDFGenerate'";
        try
        {
            if (!Directory.Exists(strDirectory))
            {
                Directory.CreateDirectory(strDirectory);
            }
        }
        catch (Exception ce)
        {
            //tc.Text = "Unable to create directory to save generated PDF files";
        }
        if (!Page.IsPostBack) //loaded first time...
        {
            //MessageBox.Show("Fires from a PAGE REFRESH or FIRST VISIT");
            BindData();
        }
        else //loaded after an event (button click, link click, etc.)
        {
            //MessageBox.Show("Fires from an EVENT");
        }
    }
    protected void BindData()
    {
        try
        {
            filePaths = Directory.GetFiles(@"C:'PDFGenerate");
            files = new List<ListItem>();
            foreach (string filePath in filePaths)
            {
                files.Add(new ListItem(Path.GetFileName(filePath), File.GetLastWriteTime(filePath).ToString()));
            }
            GridView1.DataSource = files;
            GridView1.DataBind();
            Session["fileData"] = files;
        }
        catch (Exception ce)
        {
        }
        //MessageBox.Show(files.Count() + ""); // displays the count for the files being displayed
    }
    protected void GridView1_Sorting(object server, GridViewSortEventArgs e)
        {
            DataBind();
            string strSortExpression = e.SortExpression;
            switch (strSortExpression)
            {
                case "FileName":
                    if (e.SortExpression == (string)ViewState["SortColumn"])
                    {
                        // We are resorting the same column, so flip the sort direction
                        e.SortDirection =
                            ((SortDirection)ViewState["SortColumnDirection"] == SortDirection.Ascending) ?
                            SortDirection.Descending : SortDirection.Ascending;
                    }
                    if (e.SortDirection == SortDirection.Ascending)
                    {
                        //MessageBox.Show("ASC");
                        var dataTable = ToDataTable((IList<ListItem>)Session["fileData"]);
                        var dataView = new DataView(dataTable);
                        dataView.Sort = string.Format("{0} {1}", "Text", e.SortDirection == SortDirection.Ascending ? "ASC" : "DESC");
                        GridView1.DataSource = dataView;
                        GridView1.DataBind();
                    }
                    else
                    {
                        //MessageBox.Show("DESC");
                        var dataTable = ToDataTable((IList<ListItem>)Session["fileData"]);
                        var dataView = new DataView(dataTable);
                        dataView.Sort = string.Format("{0} {1}", "Text", e.SortDirection == SortDirection.Descending ? "DESC" : "ASC");
                        GridView1.DataSource = dataView;
                        GridView1.DataBind();
                    }
                    ViewState["SortColumn"] = e.SortExpression;
                    ViewState["SortColumnDirection"] = e.SortDirection;
                break;
                case "FileDate":
                    if (e.SortExpression == (string)ViewState["SortColumn"])
                    {
                        // We are resorting the same column, so flip the sort direction
                        e.SortDirection =
                            ((SortDirection)ViewState["SortColumnDirection"] == SortDirection.Ascending) ?
                            SortDirection.Descending : SortDirection.Ascending;
                    }
                    if (e.SortDirection == SortDirection.Ascending)
                    {
                        var dataTable = ToDataTable((IList<ListItem>)Session["fileData"]);
                        var dataView = new DataView(dataTable);
                        dataView.Sort = string.Format("{0} {1}", "Value", e.SortDirection == SortDirection.Ascending ? "ASC" : "DESC");
                        GridView1.DataSource = dataView;
                        GridView1.DataBind();
                    }
                    else
                    {
                        var dataTable = ToDataTable((IList<ListItem>)Session["fileData"]);
                        var dataView = new DataView(dataTable);
                        dataView.Sort = string.Format("{0} {1}", "Value", e.SortDirection == SortDirection.Descending ? "DESC" : "ASC");
                        GridView1.DataSource = dataView;
                        GridView1.DataBind();
                    }
                    ViewState["SortColumn"] = e.SortExpression;
                    ViewState["SortColumnDirection"] = e.SortDirection;
                break;
            }
        }
    public DataTable ToDataTable(IList<ListItem> data)
        {
            var table = new DataTable();
            table.Columns.Add("Value", typeof(string));
            table.Columns.Add("Text", typeof(string));
            foreach (var item in data)
            {
                var row = table.NewRow();
                row["Value"] = item.Value;
                row["Text"] = item.Text;
                table.Rows.Add(row);
            }
            return table;
        }

如何在GridView中允许排序

虽然不建议在视图的代码后面放置逻辑,但您可以使用以下代码实现:

protected void GridView1_Sorting(object server, GridViewSortEventArgs e)
{
    switch (e.SortExpression)
    {
        case "FileName":
            var dataTable = ToDataTable((IList<ListItem>)Session["fileData"]);
            var dataView = new DataView(dataTable);
            dataView.Sort = string.Format("{0} {1}", 
                e.SortExpression, 
                e.SortDirection == SortDirection.Ascending 
                    ? "ASC" : "DESC");
            GridView1.DataSource = dataView;
            GridView1.DataBind();
        case "FileDate":
            break;
    }
}

同时,确保集合中的项目实现System.IComparable<T>

最后,添加以下代码将会话数据加载到dataTable中:

public DataTable ToDataTable(IList<ListItem> data)
{
    var table = new DataTable();
    table.Columns.Add("Value", typeof(string));
    table.Columns.Add("Text", typeof(string));
    foreach (var item in data)
    {
        var row = table.NewRow();
        row["Value"] = item.Value;
        row["Text"] = item.Text;
        table.Rows.Add(row);
    }
    return table;
}

要使代码按照我之前回答的讨论中所要求的加载排序,请执行以下操作:

创建一个名为sort的方法:

public void Sort(IList<ListItem> items, SortDirection direction)
{
    var dataTable = ToDataTable(items);
    var dataView = new DataView(dataTable);
    dataView.Sort = string.Format("{0} {1}", "Text",
        direction == SortDirection.Ascending ? "ASC" : "DESC");
    GridView1.DataSource = dataView;
    GridView1.DataBind();
}

更改BindData的实现为:

protected void BindData()
{
    try
    {
        filePaths = Directory.GetFiles(@"C:'PDFGenerate");
        files = new List<ListItem>();
        foreach (string filePath in filePaths)
        {
            files.Add(new ListItem(Path.GetFileName(filePath), File.GetLastWriteTime(filePath).ToString()));
        }
        Session["fileData"] = files;
        Sort(files, SortDirection.Descending);
    }
    catch (Exception ce)
    {
    }
    //MessageBox.Show(files.Count() + ""); // displays the count for the files being displayed
}

然后将GridView1_Sorting修改为:

    protected void GridView1_Sorting(object server, GridViewSortEventArgs e)
    {
        string strSortExpression = e.SortExpression;
        switch (strSortExpression)
        {
            case "FileName":
            case "FileDate":
                if (e.SortExpression == (string)ViewState["SortColumn"])
                {
                    // We are resorting the same column, so flip the sort direction
                    e.SortDirection =
                        ((SortDirection)ViewState["SortColumnDirection"] == SortDirection.Ascending) ?
                        SortDirection.Descending : SortDirection.Ascending;
                }
                Sort((IList<ListItem>)Session["fileData"], e.SortDirection);
                ViewState["SortColumn"] = e.SortExpression;
                ViewState["SortColumnDirection"] = e.SortDirection;
            break;
        }
    }

你必须设置GridView属性:

GridView1.AllowSorting="true"

在后面的代码中(Page_Load事件),或在Page html中:其余的详细信息见http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.allowsorting%28v=vs.110%29.aspx