none
grdiview根据多栏目进行排序问题 RRS feed

  • 问题

  • 大神们好,
    我想知道如何实现grdiview根据多栏目进行排序。
    比如我的表中有ID,Name 等等
    我想要可以根据ID排序,然后再根据Name排序。

    请问如何实现

    谢谢
    2016年11月1日 0:55

全部回复

  • GridView无法直接实现多列排序。

    你恐怕:

    1)直接使用SQL多列排序,绑定到GridView。

    2)或者使用DefaultView设置多列排序。http://blog.csdn.net/bradwarden/article/details/7212655


    ASP.NET Forum
    StackOverFlow
    FreeRice Donate
    Issues to report


    2016年11月1日 3:35
  • 你好,

    像ThankfulHeart所说的一样,Grdiview中是没有多栏目排序这一个功能的,你得要自己添加。

    你可以创建一个自定义控件继承Grdiview在其中你可以写一些多栏目排序的事件。

    如何引用自定义控件,你可以参照如下链接:

    http://blog.csdn.net/anihasiyou/article/details/8508379

    自定义Gridview你可以参照下列代码:

    自定义Grdiview:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Text;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace MCNGridView
    {
        public class MCNGridView : GridView
        {
            bool _ShowSortSequence = false;
            bool _EnableMultiColumnSorting = false;
            string _SortAscImageUrl = string.Empty;
            string _SortDescImageUrl = string.Empty;
            #region Properties
            /// <summary>
            /// 启用/禁用多列排序。
            /// </summary>
            [
            Description("Sorting On more than one column is enabled or not"),
            Category("Behavior"),
            DefaultValue("false"),
            ]
            public bool EnableMultiColumnSorting
            {
                get { return _EnableMultiColumnSorting; }
                set { AllowSorting = true; _EnableMultiColumnSorting = value; }
            }
            /// <summary>
            /// 启用/禁用排序顺序可见性。
            /// </summary>
            [
            Description("Show Sort Sequence or not"),
            Category("Behavior"),
            DefaultValue("false"),
            ]
            public bool ShowSortSequence
            {
                get { return _ShowSortSequence; }
                set { _ShowSortSequence = value; }
            }
            /// <summary>
            /// 获取/设置用于显示升序排序顺序的图像。
            /// </summary>
            [
            Description("Image to display for Ascending Sort"),
            Category("Misc"),
            Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor)),
            DefaultValue(""),
    
            ]
            public string SortAscImageUrl
            {
                get { return _SortAscImageUrl; }
                set { _SortAscImageUrl = value; }
            }
            /// <summary>
            /// 获取/设置用于显示降序排列顺序的图像。
            /// </summary>
            [
            Description("Image to display for Descending Sort"),
            Category("Misc"),
            Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor)),
            DefaultValue(""),
            ]
            public string SortDescImageUrl
            {
                get { return _SortDescImageUrl; }
                set { _SortDescImageUrl = value; }
            }
            #endregion
    
            #region Override Events
    
            protected override void OnSorting(GridViewSortEventArgs e)
            {
                if (EnableMultiColumnSorting)
                    e.SortExpression = GetSortExpression(e);
                base.OnSorting(e);
            }
    
            protected override void OnRowCreated(GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.Header)
                {
                    if (SortExpression != String.Empty)
                        ShowSortOrderImages(SortExpression, e.Row);
                }
                base.OnRowCreated(e);
            }
    
            #endregion
    
            #region Protected Methods
            /// <summary>
            /// 从现有的Gridview排序表达式中获取排序表达式
            /// </summary>
            protected string GetSortExpression(GridViewSortEventArgs e)
            {
                string[] sortColumns = null;
                string sortAttribute = SortExpression;
    
                //检查我们是否已经在Grid View中存在现有的排序顺序。
                //如果是这样,将排序列转换为数组
                if (sortAttribute != String.Empty)
                {
                    sortColumns = sortAttribute.Split(",".ToCharArray());
                }
    
                //如果用户单击现有排序顺序中的列。
                //切换排序顺序或从相应的排序中删除列
    
                if (sortAttribute.IndexOf(e.SortExpression) > 0 || sortAttribute.StartsWith(e.SortExpression))
                    sortAttribute = UpdateSortExpression(sortColumns, e.SortExpression);
                else
                    sortAttribute += String.Concat(",", e.SortExpression, " ASC ");
                return sortAttribute.TrimStart(",".ToCharArray()).TrimEnd(",".ToCharArray());
    
            }
            /// <summary>
            ///  切换排序顺序或从排序中删除列
            /// </summary>
            protected string UpdateSortExpression(string[] sortColumns, string sortExpression)
            {
                string ascSortExpression = String.Concat(sortExpression, " ASC ");
                string descSortExpression = String.Concat(sortExpression, " DESC ");
                for (int i = 0; i < sortColumns.Length; i++)
                {
                    if (ascSortExpression.Equals(sortColumns[i]))
                        sortColumns[i] = descSortExpression;
                    else if (descSortExpression.Equals(sortColumns[i]))
                        Array.Clear(sortColumns, i, 1);
                }
                return String.Join(",", sortColumns).Replace(",,", ",").TrimStart(",".ToCharArray());
            }
            /// <summary>
            /// 查找当前排序表达式以确定特定项目的顺序。
            /// </summary>
            protected void SearchSortExpression(string[] sortColumns, string sortColumn, out string sortOrder, out int sortOrderNo)
            {
                sortOrder = "";
                sortOrderNo = -1;
                for (int i = 0; i < sortColumns.Length; i++)
                {
                    if (sortColumns[i].StartsWith(sortColumn))
                    {
                        sortOrderNo = i + 1;
                        if (EnableMultiColumnSorting)
                            sortOrder = sortColumns[i].Substring(sortColumn.Length).Trim();
                        else
                            sortOrder = ((SortDirection == SortDirection.Ascending) ? "ASC" : "DESC");
                    }
                }
            }
            /// <summary>
            /// 显示下拉框图片
            /// </summary>
            protected void ShowSortOrderImages(string sortExpression, GridViewRow dgItem)
            {
                string[] sortColumns = sortExpression.Split(",".ToCharArray());
    
                for (int i = 0; i < dgItem.Cells.Count; i++)
                {
                    if (dgItem.Cells[i].Controls.Count > 0 && dgItem.Cells[i].Controls[0] is LinkButton)
                    {
                        string sortOrder;
                        int sortOrderNo;
                        string column = ((LinkButton)dgItem.Cells[i].Controls[0]).CommandArgument;
                        SearchSortExpression(sortColumns, column, out sortOrder, out sortOrderNo);
                        if (sortOrderNo > 0)
                        {
                            string sortImgLoc = (sortOrder.Equals("ASC") ? SortAscImageUrl : SortDescImageUrl);
    
                            if (sortImgLoc != String.Empty)
                            {
                                Image imgSortDirection = new Image();
                                imgSortDirection.ImageUrl = sortImgLoc;
                                dgItem.Cells[i].Controls.Add(imgSortDirection);
                                if (EnableMultiColumnSorting && _ShowSortSequence)
                                {
                                    Label lblSortOrder = new Label();
                                    lblSortOrder.Font.Size = FontUnit.XSmall;
                                    lblSortOrder.Font.Name = "verdana";
                                    lblSortOrder.Text = sortOrderNo.ToString();
                                    dgItem.Cells[i].Controls.Add(lblSortOrder);
                                }
                            }
                            else
                            {
                                Label lblSortDirection = new Label();
                                lblSortDirection.Font.Size = FontUnit.XSmall;
                                lblSortDirection.Font.Name = "verdana";
                                lblSortDirection.EnableTheming = false;
                                lblSortDirection.Text = (sortOrder.Equals("ASC") ? "^" : "v");
                                dgItem.Cells[i].Controls.Add(lblSortDirection);
                                if (EnableMultiColumnSorting && _ShowSortSequence)
                                {
                                    Literal litSortSeq = new Literal();
                                    litSortSeq.Text = sortOrderNo.ToString();
                                    dgItem.Cells[i].Controls.Add(litSortSeq);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    #endregion

    Aspx页面:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GridViewMultiColumnSort.Default" %>
    <%@ Register Assembly="MCNGridView" namespace="MCNGridView" tagprefix="MCN" %>
      <MCN:MCNGridView ID="MCNGridView1" runat="server" EnableMultiColumnSorting="True"        
            AutoGenerateColumns="False" DataKeyNames="CustomerID"  ShowSortSequence="True"
            DataSourceID="SqlDataSource1" CellPadding="4" 
            ForeColor="#333333" GridLines="None" AllowPaging="True" 
            SortAscImageUrl="~/Images/asc.png" SortDescImageUrl="~/Images/desc.png">
            <RowStyle BackColor="#EFF3FB" />
            <Columns>
                <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" 
                    SortExpression="CustomerID">
                </asp:BoundField>
                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" 
                    SortExpression="CompanyName" />
                <asp:BoundField DataField="ContactName" HeaderText="ContactName" 
                    SortExpression="ContactName" />
                <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle" 
                    SortExpression="ContactTitle" />
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                <asp:BoundField DataField="Region" HeaderText="Region" 
                    SortExpression="Region" />
                <asp:BoundField DataField="PostalCode" HeaderText="PostalCode" 
                    SortExpression="PostalCode" />
                <asp:BoundField DataField="Country" HeaderText="Country" 
                    SortExpression="Country" />
            </Columns>
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </MCN:MCNGridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" 
            SelectCommand="SELECT * FROM [Customers]"></asp:SqlDataSource>


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2016年11月1日 13:13
  • 你好 Anne_Wx,

    这个问题解决了吗?现在有什么进展? 谢谢!

    Best regards,

    yanjin 


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2016年11月11日 9:47