如何在GridView中自动排序IEnumerable ?

时间:2021-07-06 14:22:35

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

如何对返回一个列表的BLL (CustomerList: GridView中的list)进行自动排序?

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

Customer是我自己的强类型类,CustomerList是客户列表。

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.

我知道一种方法是在GridView中将allowsort属性设置为true,并处理onsort事件并调用CustomerList类中定义的排序方法。

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.

但是我想要一个自动的解决方案,因为我不需要处理onsort事件,它应该像GridView处理DataView、DataTable和DataSet的自动排序一样。

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

我需要在我的CustomerList或Customer类上实现一个接口来启用该功能吗?

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

alt文本http://img260.imageshack.us/img260/3373/aa479347gridviewfg21enu.gif

2 个解决方案

#1


7  

Okay I figured it out. Here is the solution :

我算出来了。下面是解决方案:

  1. Tie the BLL to an ObjectDataSource.
  2. 将BLL绑定到ObjectDataSource。
  3. Provide overloaded methods for the select method in your BLL, to support paging and sorting.
  4. 为BLL中的select方法提供重载方法,以支持分页和排序。
  5. Provide the SortParameterName in the ObjectDataSource. This is the the name of the string input parameter of your select method in your BLL.
  6. 在ObjectDataSource中提供SortParameterName。这是您的BLL中的select方法的字符串输入参数的名称。

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

更多信息请参见: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:

这是一个例子,这只是一个quck的例子演示我不支持排序方向,或者优化代码等:

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 :

在ASPX页面:

  <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

更多信息请参见:http://msdn.microsoft.com/en-us/library/aa479347.aspx

#2


0  

You can do the same logic in DAL by storing the sortexpression and direction in sessions. Obtain Sortexpression n direction from gridview sorting method and do sorting in DAL using these paramters .BUT u hav to take care of the exception in setting e.cancel=true

通过在会话中存储sortexpression和方向,可以在DAL中实现相同的逻辑。从gridview排序方法中获取Sortexpression n方向,并使用这些参数进行排序,但是在设置e.cancel=true时,您需要处理异常

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
     \\ Take sortexpression n direction
       e.cancel = true 
        }

also refer http://forums.asp.net/t/1344883.aspx

也请参阅http://forums.asp.net/t/1344883.aspx

#1


7  

Okay I figured it out. Here is the solution :

我算出来了。下面是解决方案:

  1. Tie the BLL to an ObjectDataSource.
  2. 将BLL绑定到ObjectDataSource。
  3. Provide overloaded methods for the select method in your BLL, to support paging and sorting.
  4. 为BLL中的select方法提供重载方法,以支持分页和排序。
  5. Provide the SortParameterName in the ObjectDataSource. This is the the name of the string input parameter of your select method in your BLL.
  6. 在ObjectDataSource中提供SortParameterName。这是您的BLL中的select方法的字符串输入参数的名称。

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

更多信息请参见: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:

这是一个例子,这只是一个quck的例子演示我不支持排序方向,或者优化代码等:

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 :

在ASPX页面:

  <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

更多信息请参见:http://msdn.microsoft.com/en-us/library/aa479347.aspx

#2


0  

You can do the same logic in DAL by storing the sortexpression and direction in sessions. Obtain Sortexpression n direction from gridview sorting method and do sorting in DAL using these paramters .BUT u hav to take care of the exception in setting e.cancel=true

通过在会话中存储sortexpression和方向,可以在DAL中实现相同的逻辑。从gridview排序方法中获取Sortexpression n方向,并使用这些参数进行排序,但是在设置e.cancel=true时,您需要处理异常

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
     \\ Take sortexpression n direction
       e.cancel = true 
        }

also refer http://forums.asp.net/t/1344883.aspx

也请参阅http://forums.asp.net/t/1344883.aspx