如何在GridView中进行排序

时间:2014-06-30 13:55:40

标签: c# asp.net

我有以下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;
        }

3 个答案:

答案 0 :(得分:3)

虽然不建议在视图的代码隐藏中放置逻辑,但您可以使用以下代码实现此目的:

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

答案 1 :(得分:1)

要按照我之前的答案讨论中的要求对代码进行排序,请执行以下操作:

创建一个名为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;
        }
    }

答案 2 :(得分:-1)

您必须设置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