NEWS

[C#] Hướng dẫn sắp xếp column listview (sort column header listview)

[C#] Hướng dẫn sắp xếp column listview (sort column header listview)
Đăng bởi: Thảo Meo - Lượt xem: 15085 10:57:39, 28/03/2018C#   In bài viết

Xin chào các bạn, hôm nay mình sẽ tiếp tục hướng dẫn các bạn cách sort dữ liệu trên column của listview C#.

Sort list view trên C#, cũng tương tự như các bạn sử dụng ứng dụng File Explorer của Windows, chúng sẽ cho chúng ta dễ dàng sắp xếp dữ liệu theo các trường.

Ví dụ: Muốn sắp xếp danh sách nhân viên từ A->Z, hoặc sắp xếp lại theo tuổi từ nhỏ ->lớn...

Dưới đây là giao diện demo ứng dụng Sort Column Listview C#

sort column list view trong c#

- Đầu tiên các bạn cần tạo một class ItemComparer.cs được implement từ Interface IComparer.

Source code class ItemComparer.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Windows.Forms;

namespace ListViewSortAnyColumn
{
    public class ItemComparer : IComparer
    {
        //column used for comparison
        public int Column { get; set; }

        //Order of sorting
        public SortOrder Order { get; set; }

        public ItemComparer(int colIndex)
        {
            Column = colIndex;
            Order = SortOrder.None;

        }
        public int Compare(object a, object b)
        {
            int result;

            ListViewItem itemA = a as ListViewItem;
            ListViewItem itemB = b as ListViewItem;
            if (itemA == null && itemB == null)
                result = 0;
            else if (itemA == null)
                result = -1;
            else if (itemB == null)
                result = 1;

            if (itemA == itemB)
                result = 0;

            // datetime comparison
            DateTime x1, y1;
            // Parse the two objects passed as a parameter as a DateTime.
            if (!DateTime.TryParse(itemA.SubItems[Column].Text, out x1))
                x1 = DateTime.MinValue;
            if (!DateTime.TryParse(itemB.SubItems[Column].Text, out y1))
                y1 = DateTime.MinValue;
            result = DateTime.Compare(x1, y1);

            if (x1 != DateTime.MinValue && y1 != DateTime.MinValue)
                goto done;

            //numeric comparison
            decimal x2, y2;
            if (!Decimal.TryParse(itemA.SubItems[Column].Text, out x2))
                x2 = Decimal.MinValue;
            if (!Decimal.TryParse(itemB.SubItems[Column].Text, out y2))
                y2 = Decimal.MinValue;
            result = Decimal.Compare(x2, y2);

            if (x2 != Decimal.MinValue && y2 != Decimal.MinValue)
                goto done;

            //alphabetic comparison
            result = String.Compare(itemA.SubItems[Column].Text, itemB.SubItems[Column].Text);



        done:
            // if sort order is descending.
            if (Order == SortOrder.Descending)
                // Invert the value returned by Compare.
                result *= -1;
            return result;

        }
    }
}

- Tiếp tục, là source code C# cho form main.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ListViewSortAnyColumn
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //fill the list with data
            FillItems();
        }

        private void listViewSample_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            ItemComparer sorter = listViewSample.ListViewItemSorter as ItemComparer;

            if (sorter == null)
            {
                sorter = new ItemComparer(e.Column);
                sorter.Order = SortOrder.Ascending;
                listViewSample.ListViewItemSorter = sorter;
            }
            // if clicked column is already the column that is being sorted
            if (e.Column == sorter.Column)
            {
                // Reverse the current sort direction
                if (sorter.Order == SortOrder.Ascending)
                    sorter.Order = SortOrder.Descending;
                else
                    sorter.Order = SortOrder.Ascending;
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                sorter.Column = e.Column;
                sorter.Order = SortOrder.Ascending;
            }
            listViewSample.Sort();
        }

        private void FillItems()
        {
            // Add items
            ListViewItem item1 = new ListViewItem("Nguyễn Thảo");
            item1.SubItems.Add("10/11/2000");
            item1.SubItems.Add("Email@domain.com");
            item1.SubItems.Add("123.456");

            ListViewItem item2 = new ListViewItem("Hoàng Thị Thảo");
            item2.SubItems.Add("12/12/2010");
            item2.SubItems.Add("test@test.com");
            item2.SubItems.Add("123.4561");

            ListViewItem item3 = new ListViewItem("Võ Sơn Băng");
            item3.SubItems.Add("12/01/1800");
            item3.SubItems.Add("sample@Sample.net");
            item3.SubItems.Add("123.4559");

            ListViewItem item4 = new ListViewItem("Nguyễn Đình Tuyên");
            item4.SubItems.Add("05/30/1900");
            item4.SubItems.Add("user@sample.com");
            item4.SubItems.Add("-123.456000");

            ListViewItem item5 = new ListViewItem("Cái Trí Minh");
            item5.SubItems.Add("05/30/1900");
            item5.SubItems.Add("user@sample.com");
            item5.SubItems.Add("-123.456000");

            // Add the items to the ListView.
            listViewSample.Items.AddRange(
                                    new ListViewItem[] { item1, item2, item3, item4, item5 });
        }
    }
}

CHÚC CÁC BẠN THÀNH CÔNG!

DOWNLOAD SOURCE

Tags: listview

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn sắp xếp column listview (sort column header listview)
Đăng bởi: Thảo Meo - Lượt xem: 15085 10:57:39, 28/03/2018C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.