C# winform 中datagridview ,如何实现点击列头,对应的列自动排序?

如题所述

在使用 DataGridView时,对于数值列,默认的排序方式仍然是按照字符串方式进行

如果需要按照数值型进行排序,有几种办法,其中一种就是重载SortCompare方法

//重载_SortCompare方法

private void DataGridView1_SortCompare(object sender,DataGridViewSortCompareEventArgs e)

{

//   如果是学号或成绩列,则按浮点数处理

if(e.Column.Name=="学号"|| e.Column.Name=="成绩")

{

e.SortResult = (Convert.ToDouble(e.CellValue1) - Convert.ToDouble(e.CellValue2) > 0) ? 1 : (Convert.ToDouble(e.CellValue1) - Convert.ToDouble(e.CellValue2) < 0)?-1:0;

}

//否则,按字符串比较

else

{

e.SortResult = System.String.Compare(Convert.ToString(e.CellValue1), Convert.ToString(e.CellValue2));

}

// 如果发现两行相同,则按学号排序  

if (e.SortResult == 0 && e.Column.Name != "学号")

{

e.SortResult = Convert.ToInt32(DataGridView1.Rows[e.RowIndex1].Cells["学号"].Value.ToString()) -

Convert.ToInt32(DataGridView1.Rows[e.RowIndex2].Cells["学号"].Value.ToString());

}
e.Handled = true;//不能省掉,不然没效果
}  

温馨提示:答案为网友推荐,仅供参考
相似回答