这里只贴主要代码,dataList是已添加数据的全局变量,绑定数据源 datagridview1.DataSource = dataList,以下是核心代码。
实现点击列表头实现自定义排序
private int _sorterOrder; //1表示升序,0表示降序 private int _previousIndex = -1; //记录前一次点击的列索引 private datagridview1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { //判断列标头是否被连续点击,是则改变上次排序规则,否则按升序排序 if (this._previousIndex == e.ColumnIndex) { this._sorterOrder = -this._sorterOrder; } else { this._sorterOrder = 1; } this._previousIndex = e.ColumnIndex;
ListComparison(datagridview1.Columns[e.ColumnIndex].DataPropertyName); }
实现List集合根据传入的属性名进行排序
/// <summary> /// List集合比较器 /// </summary> /// <param name="propName">属性名</param> private void ListComparison(string propName) { Type type = typeof(MyModel); PropertyInfo property = type.GetProperty(propName); List<MyModel> modelList = datagridview1.DataSource as List<MyModel>; modelList.Sort((x, y) => { string value1 = property.GetValue(x, null).ToString(); string value2 = property.GetValue(y, null).ToString(); double number1, number2; //如果属性值为数字则转换为浮点数进行比较,否则按照字符串比较 if (double.TryParse(value1, out number1) && double.TryParse(value2, out number2)) { return this._sorterOrder == 1 ? number1.CompareTo(number2) : number2.CompareTo(number1); } return this._sorterOrder == 1 ? value1.CompareTo(value2) : value2.CompareTo(value1); }); }