DataGridView 自定义排序,对多列尤其简单。

先创建一个静态类,用以实现扩展方法Sort。

public static class MySort { public static void Sort(this DataGridView dgv, Comparison comparison) { dgv.Sort(new RowCompare(comparison)); } public class RowCompare : IComparer { Comparison comparison; public RowCompare(Comparison comparison) { this.comparison = comparison; } #region IComparer 成员 public int Compare(object x, object y) { return comparison((DataGridViewRow)x, (DataGridViewRow)y); } #endregion } }

下面是对datagridview前三列排序的例子

Comparison compare=(a,b)=> { if(a.Cells[0].Value.Equals(b.Cells[0].Value)) { if(a.Cells[1].Value.Equals(b.Cells[1].Value)) return a.Cells[2].Value.ToString().CompareTo(b.Cells[2].Value.ToString()); return a.Cells[1].Value.ToString().CompareTo(b.Cells[1].Value.ToString()); } return a.Cells[0].Value.ToString().CompareTo(b.Cells[0].Value.ToString()); }; dataGridView1.Sort(compare);  

你可能感兴趣的:(c#,WinForm)