4

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>

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
}

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;
        }
5
  • Sort whatever your datasource is and feed it back to your grid. What's the problem?
    – Rick S
    Jun 30, 2014 at 14:00
  • I updated my question to include what my data source is. they are files from a folder. Jun 30, 2014 at 14:02
  • I updated my question. The GridView is displaying file name in one column and file modified date in another column from a specified folder. I would like to let user sort each column with either the file name or file date. Jun 30, 2014 at 14:18
  • But I do not see sorting happening on Session["fileData"] before assigning to gridview in GridView1_Sorting event. Did you try converting Session["fileData"] to relevant type and do sort perhaps using LINQ and then assign to GridView?
    – Siva Gopal
    Jun 30, 2014 at 15:14
  • I am not sure how to achieve that... Jun 30, 2014 at 15:15

3 Answers 3

3

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

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

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

To make the code sort on load as requested in a discussion on my previous answer, do the following:

Make a method called 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();
}

Change BindData's implementation to:

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
}

Then, change GridView1_Sorting to:

    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
  • Thanks!...It will do both for FileName and FileDate? I would like the FileName to be sorted from new to old on page load and the user can click on FileName or FileDate to sort afterward. Is that what the code is doing? It is only doing the FileName. I can use a SWITCH to do both... Jun 30, 2014 at 17:50
  • I did it... I used a second function and used a SWITCH to pass a string of the type of column it is. Thanks. Jun 30, 2014 at 17:59
-1

You have to set GridView property:

GridView1.AllowSorting="true"

in either code behind (Page_Load event), or in the Page html: the rest is detailed in http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.allowsorting%28v=vs.110%29.aspx

2
  • 1
    I have added the property. Jun 30, 2014 at 14:23
  • 1
    I added the property but it's not working because I am not sure how to achieve the order method for my purpose. I did upvote and will accept once I have it working from the link you posted. Or if someone else gives something more. Thanks. Jun 30, 2014 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.