如何允许在GridView中排序 [英] How to allow sorting in GridView

查看:65
本文介绍了如何允许在GridView中排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following GirdView which displays some files with its modified date:

<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:

I am populating the GridView with the following code:

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数据源,因此我不确定如何处理它:

I allowed the sorting method in the GridView and also added the sort expression. I am trying to write the C# code which will allow sorting but I'm not sure how I would go about it as I am not using a SQL data source:

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;
        }
    }

更新:如何使它正常工作...

UPDATE: How I was able to get it to work correctly...

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;
        }

推荐答案

尽管不建议将逻辑放在视图的代码后方,但您可以使用以下代码来实现:

Though it is not advised to place logic in your views' code-behind, you would achieve this with the following code:

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>

Also, make sure that the items in your collection implement System.IComparable<T>

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

Finally, add the following code to load your session data into the 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;
}

这篇关于如何允许在GridView中排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆