Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable Automatic Sorting of IEnumerable Data in GridView?

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

like image 900
ace Avatar asked Mar 31 '10 02:03

ace


People also ask

How to sort the data in a GridView?

You can sort the data in ascending as well as in the descending order by clicking on the columns name of the GridView. GridView is a powerful data grid control which allows us to display the values of a data source in a table format where each column represents a field and each row represents a record.

What is the sort event in the datagridview interface?

This event is raised when you call the overloaded version of the Sort method mentioned above (by the way, it also works when we click a column's header of a DataGridView in the interface to sort it by that column).

What is the default Default for sorting in GridView control?

The default is false. The following example demonstrates how to use the AllowSorting property to enable sorting in a GridView control when automatically generated columns are used.

What is the hyperlink sort event in GridView?

Occurs when the hyperlink to sort a column is clicked, but after the GridView control handles the sort operation. This event is commonly used to perform a task after the user clicks a hyperlink to sort a column. Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation.


1 Answers

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

like image 150
ace Avatar answered Oct 21 '22 17:10

ace