簡體   English   中英

C#-排序datagridview的麻煩

[英]C# - troubles with sorting datagridview

我已經搜尋了我的屁股來解決我的問題。 我已經開發了帶有一些datagridviews的ac#Winforms程序。

問題是我希望成為能夠通過單擊列標題對datagridview進行排序的用戶(我認為這將是標准的……),但是它不起作用。

我嘗試了dgv.Sort方法,但這引發了一個例外,即必須將datagridview綁定到IBindingList,但是我不知道如何執行該操作,並且我真的不想重新開發所有內容。

這是我填充dgv的方法。

我有某些自定義對象,並將它們放入列表中。 當此列表完全填充后,我將其設置為dgv的數據源。

list.Add(costumobject);
.
.
.
dgv.DataSource = list;

您能告訴我一種使排序功能起作用的快速方法嗎?

親切的問候,

List<T>不支持直接排序。

相反,您可以使用Linq例程進行排序。

但是,您將需要包括一個排序字段檢查,該檢查與列數一樣長。

不知道您的customobject類,讓我們嘗試使用Name類:

class Name
{
    public string first { get; set; }
    public string last { get; set; }
    public string middle { get; set; }

    public Name (string f, string m, string l)
    {
        first = f; middle = m; last = l;
    }
}

現在,讓我們對ColumnHeaderMouseClick事件進行編碼:

private void dataGridView1_ColumnHeaderMouseClick(object sender, 
                           DataGridViewCellMouseEventArgs e)
{
    List<Name> names = dataGridView1.DataSource as List<Name>;
    string col = dataGridView2.Columns[e.ColumnIndex].DataPropertyName;
    string order =  " ASC";
    if (dataGridView1.Tag != null) 
        order = dataGridView1.Tag.ToString().Contains(" ASC") ? " DESC" : " ASC";

    dataGridView1.Tag = col + order;

    if (order.Contains(" ASC"))
    names = names.OrderBy(x => col == "first"? x.first 
                             : col == "last" ? x.last : x.middle).ToList();  
    else
    names = names.OrderByDescending(x => col == "first"? x.first : 
                                         col == "last" ? x.last : x.middle).ToList();  

    dataGridView1.DataSource = names;
}

請注意,我將當前的排序列和順序存儲在DGV的Tag 您可以將其移動到類級別的變量或其他位置。 不幸的是,無法設置DGV的SortOrder屬性。

創建一個SortableBindingList而不是一個List。

using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace YourNamespace
{
    /// <summary>
    /// Provides a generic collection that supports data binding and additionally supports sorting.
    /// See http://msdn.microsoft.com/en-us/library/ms993236.aspx
    /// If the elements are IComparable it uses that; otherwise compares the ToString()
    /// </summary>
    /// <typeparam name="T">The type of elements in the list.</typeparam>
    public class SortableBindingList<T> : BindingList<T> where T : class
    {
        private bool _isSorted;
        private ListSortDirection _sortDirection = ListSortDirection.Ascending;
        private PropertyDescriptor _sortProperty;

        /// <summary>
        /// Initializes a new instance of the <see cref="SortableBindingList{T}"/> class.
        /// </summary>
        public SortableBindingList()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SortableBindingList{T}"/> class.
        /// </summary>
        /// <param name="list">An <see cref="T:System.Collections.Generic.IList`1" /> of items to be contained in the <see cref="T:System.ComponentModel.BindingList`1" />.</param>
        public SortableBindingList(IList<T> list) : base(list)
        {
        }

        /// <summary>
        /// Gets a value indicating whether the list supports sorting.
        /// </summary>
        protected override bool SupportsSortingCore
        {
            get { return true; }
        }

        /// <summary>
        /// Gets a value indicating whether the list is sorted.
        /// </summary>
        protected override bool IsSortedCore
        {
            get { return _isSorted; }
        }

        /// <summary>
        /// Gets the direction the list is sorted.
        /// </summary>
        protected override ListSortDirection SortDirectionCore
        {
            get { return _sortDirection; }
        }

        /// <summary>
        /// Gets the property descriptor that is used for sorting the list if sorting is implemented in a derived class; otherwise, returns null
        /// </summary>
        protected override PropertyDescriptor SortPropertyCore
        {
            get { return _sortProperty; }
        }

        /// <summary>
        /// Removes any sort applied with ApplySortCore if sorting is implemented
        /// </summary>
        protected override void RemoveSortCore()
        {
            _sortDirection = ListSortDirection.Ascending;
            _sortProperty = null;
            _isSorted = false; //thanks Luca
        }

        /// <summary>
        /// Sorts the items if overridden in a derived class
        /// </summary>
        /// <param name="prop"></param>
        /// <param name="direction"></param>
        protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
        {
            _sortProperty = prop;
            _sortDirection = direction;

            List<T> list = Items as List<T>;
            if (list == null) return;
            list.Sort(Compare);
            _isSorted = true;
            //fire an event that the list has been changed.
            OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
        }

        private int Compare(T lhs, T rhs)
        {
            var result = OnComparison(lhs, rhs);
            //invert if descending
            if (_sortDirection == ListSortDirection.Descending)
                result = -result;
            return result;
        }

        private int OnComparison(T lhs, T rhs)
        {
            object lhsValue = lhs == null ? null : _sortProperty.GetValue(lhs);
            object rhsValue = rhs == null ? null : _sortProperty.GetValue(rhs);
            if (lhsValue == null)
            {
                return (rhsValue == null) ? 0 : -1; //nulls are equal
            }

            if (rhsValue == null)
            {
                return 1; //first has value, second doesn't
            }

            if (lhsValue is IComparable)
            {
                return ((IComparable)lhsValue).CompareTo(rhsValue);
            }

            if (lhsValue.Equals(rhsValue))
            {
                return 0; //both are the same
            }

            //not comparable, compare ToString
            return lhsValue.ToString().CompareTo(rhsValue.ToString());
        }
    }
}

更改數據源后您是否嘗試過刷新數據網格?

list.Add(costumobject);
.
.
.
dgv.DataSource = list;
dgv.Refresh();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM