C# – How to enable Automatic Sorting of IEnumerable Data in GridView

asp.netcgridviewienumerablesorting

How can I enable automatic sorting of my BLL which returns a list, CustomerList:List in a GridView?

Customer is my own strongly typed class and CustomerList is a List of customers.

I know one approach is to set the AllowSorting property to true in the GridView and handle the OnSorting event and calling a sorting method defined in my CustomerList class.

However I would like a solution which is automatic in the sense that I do not have to handle the OnSorting Event, it should be like how GridView handles automatic sorting for DataView, DataTable, and DataSet.

Is there an Interface I need to implement on my CustomerList or Customer class that will enable that functionality?

alt text http://img260.imageshack.us/img260/3373/aa479347gridviewfg21enu.gif

Best Answer

Okay I figured it out. Here is the solution :

  1. Tie the BLL to an ObjectDataSource.
  2. Provide overloaded methods for the select method in your BLL, to support paging and sorting.
  3. Provide the SortParameterName in the ObjectDataSource. This is the the name of the string input parameter of your select method in your BLL.

For more information see : http://msdn.microsoft.com/en-us/library/aa479347.aspx

Here's an example, this is just a quck example for demo I did not support sort direction, or optimized the code etc:

namespace CodeSamples.DAL
{
    public static class DAL
    {
        public static CustomerList GetCustomerList(string SortExpression)
        {
            return GetCustomerList(int.MaxValue, 0, SortExpression);
        }

        public static CustomerList GetCustomerList()
        {
            return GetCustomerList(int.MaxValue, 0,String.Empty);
        }

        public static CustomerList GetCustomerList(int maximumRows, int startRowIndex, string SortExpression)
        {
            const string query = "Select * from Customers";
            CustomerList customers = new CustomerList();


            SqlConnection conn = new SqlConnection("Data Source=Win2k8;Initial Catalog=NorthWind;User ID=sa;Password=XXXXX");
            SqlCommand command = new SqlCommand(query, conn);
            conn.Open();
            SqlDataReader reader = command.ExecuteReader();

            ArrayList rows = new ArrayList();

            while (reader.Read())
            {
                object[] values = new object[reader.FieldCount];
                reader.GetValues(values);
                rows.Add(values);
            }

            conn.Close();

            int currentIndex = 0;
            int itemsRead = 0;
            int totalRecords = rows.Count;

            foreach (object[] row in rows)
            {
                if (currentIndex >= startRowIndex && itemsRead <= maximumRows)
                {
                    customers.Add(new Customer { Name = row[1].ToString(), ID = row[0].ToString(), ContactName = row[2].ToString() });
                    itemsRead++;
                }
                currentIndex++;
            }


        CustomerList sortedCustomers = new CustomerList();

        string sortBy = SortExpression;
        bool isDescending = false;

        if (SortExpression.ToLowerInvariant().EndsWith(" desc"))
        {
            sortBy = SortExpression.Substring(0, SortExpression.Length - 5);
            isDescending = true;
        }         

        var sortedList = from customer in customers
                         select customer;

        switch (sortBy)
        {
            case "ID":
                sortedList = isDescending ? sortedList.OrderByDescending(cust => cust.ID) : sortedList.OrderBy(cust => cust.ID);
                break;

            case "Name":
                sortedList = isDescending ? sortedList.OrderByDescending(cust => cust.Name) : sortedList.OrderBy(cust => cust.Name);
                break;

            case "ContactName":
                sortedList = isDescending ? sortedList.OrderByDescending(cust => cust.ContactName) : sortedList.OrderBy(cust => cust.ContactName);
                break;

        }

        foreach (Customer x in sortedList)
        {
            sortedCustomers.Add(x);
        }    

            return sortedCustomers;
        }
    }  

    public class CustomerList : List<Customer>
    {

    } 

    public class Customer
    {
        public Customer()
        {
        }

        public Customer(string Name, string id)
        {
            this.Name = Name;
            ID = id;
        }
        public string ID
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public string ContactName
        {
            get;
            set;
        }


    }
}

In the ASPX page :

  <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
            AutoGenerateColumns="False" DataSourceID="ObjectDataSource1" 
            AllowSorting="True">
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
            </Columns>
        </asp:GridView>
        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
            SelectMethod="GetCustomerList" SortParameterName="SortExpression"
            TypeName="CodeSamples.DAL.DAL">
        </asp:ObjectDataSource>

For more information see : http://msdn.microsoft.com/en-us/library/aa479347.aspx

Related Topic