最近有个新的需求就是,点击DataGridView的表头能对数据进行排序,在网站搜了半天都没有找到合适的(简单粗暴的)排序方法。只好自己摸索一下,思路如下:
1. 在点击表头的事件中获取列索引,只对特定的状态进行排序
2. 排序使用OrderBy或OrderByDescending方法
实体类School如下:
public class School
{
/// <summary>
/// 主键ID
/// </summary>
public string ID { get; set; }
/// <summary>
/// 编号
/// </summary>
public string BH { get; set; }
/// <summary>
/// 学校名称
/// </summary>
public string XXMC { get; set; }
/// <summary>
/// 学校列表
/// </summary>
public static string[] XXLB = new string[] {
"华中科技大学",
"武汉大学",
"华中农业大学",
"武汉理工大学",
"武汉科技大学",
};
/// <summary>
/// 查询
/// </summary>
/// <returns></returns>
public static List<School> Query()
{
List<School> list = new List<School>();
Random random = new Random();
for (int i = 0; i < 10; i++)
{
//生成随机数据
School item = new School()
{
ID = Guid.NewGuid().ToString(),
BH = random.Next(0,10).ToString() + random.Next(0, 10).ToString() + random.Next(0, 10).ToString() + random.Next(0, 10).ToString(),
XXMC = School.XXLB.ElementAt(random.Next(0, 4))
};
list.Add(item);
}
return list;
}
}
界面如下:
点击表头事件:
/// <summary>
/// 排序规则
/// </summary>
private bool _BH_ASC = false;
/// <summary>
/// 点击列头部
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex == 1)
{
var list = this.dataGridView1.DataSource as List<School>;
if(list != null)
{
if(_BH_ASC == false)
{
list = list.OrderBy(m => m.BH).ToList();
}
else
{
list = list.OrderByDescending(m => m.BH).ToList();
}
_BH_ASC = !_BH_ASC;
this.dataGridView1.DataSource = list;
}
}
}
效果图:
B站传送门:DataGridView点击表头排序