參考鏈接:https://blog.csdn.net/qq_42025804/article/details/97796374?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

1 using System;
2 using System.Collections;
3 using System.Collections.Generic;
4 using System.ComponentModel;
5 using System.Data;
6 using System.Drawing;
7 using System.Linq;
8 using System.Text;
9 using System.Threading.Tasks;
10 using System.Windows.Forms;
11
12 namespace MatrixDemo
13 {
14 public partial class FormPoints : Form
15 {
16 private int count = 0;
17 private bool initSet = false;
18
19 public FormPoints(List<DpMatrix.MatrixPoint> points)
20 {
21 InitializeComponent();
22 UpdatePointsDGV(points);
23 }
24
25 private void FormPoints_Load(object sender, EventArgs e)
26 {
27
28 }
29
30 private void FormPoints_Shown(object sender, EventArgs e)
31 {
32 this.PointsCountSSL.Text = this.count.ToString();
33 }
34
35 private void UpdatePointsDGV(List<DpMatrix.MatrixPoint> points)
36 {
37 this.PointsDGV.DataSource = points;
38 this.count = points.Count;
39
40 if (!initSet)
41 {
42 this.PointsDGV.Columns[0].HeaderCell.Value = "行";
43 this.PointsDGV.Columns[1].HeaderCell.Value = "列";
44 this.PointsDGV.Columns[2].HeaderCell.Value = "亮/滅";
45
46 this.PointsDGV.Columns[2].SortMode = DataGridViewColumnSortMode.NotSortable;
47
48 this.PointsDGV.Columns[0].ReadOnly = true;
49 this.PointsDGV.Columns[1].ReadOnly = true;
50 this.PointsDGV.Columns[2].ReadOnly = false;
51
52 initSet = !initSet;
53 }
54 }
55
56 //排序
57 private void PointsDGV_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
58 {
59 try
60 {
61 //取得點擊列的索引
62 int nColumnIndex = e.ColumnIndex;
63
64 List<DpMatrix.MatrixPoint> points = (List<DpMatrix.MatrixPoint>)PointsDGV.DataSource;//轉成類的list集合
65
66 if (PointsDGV.Columns[nColumnIndex].SortMode == DataGridViewColumnSortMode.NotSortable)
67 {
68 return;
69 }
70 switch (PointsDGV.Columns[nColumnIndex].HeaderCell.SortGlyphDirection)
71 {
72 case SortOrder.None:
73 case SortOrder.Ascending:
74 ListSort(points, nColumnIndex, 0);
75 PointsDGV.Columns[nColumnIndex].HeaderCell.SortGlyphDirection = SortOrder.Descending;
76 break;
77 case SortOrder.Descending:
78 ListSort(points, nColumnIndex, 1);
79 PointsDGV.Columns[nColumnIndex].HeaderCell.SortGlyphDirection = SortOrder.Ascending;
80 break;
81 }
82 }
83 catch (Exception ex)
84 {
85 MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
86 }
87
88
89 }
90
91 //0-desc;1-asc
92 private void ListSort(List<DpMatrix.MatrixPoint> points, int index, int type)
93 {
94 switch (index)
95 {
96 case 0:
97 PointsDGV.DataSource = (type == 0) ?
98 points.OrderByDescending(p => p.row).ToList() : points.OrderBy(p => p.row).ToList();
99 break;
100 case 1:
101 PointsDGV.DataSource = (type == 0) ?
102 points.OrderByDescending(p => p.col).ToList() : points.OrderBy(p => p.col).ToList();
103 break;
104 }
105 }
106 }
107 }