对数字字符串进行排序
本文关键字:排序 字符串 数字 数字字符 | 更新日期: 2023-09-27 18:27:03
我在c#中使用DatagridView
读取csv文件
单击网格顶部的标题时,数据排序不正确。
例如,它应该排序为1,2,3,4,5,etc
然而,结果是1,10,2,20,etc
。
我想我需要将它从string
转换为int
,但我不知道如何做到这一点。
这是我当前的代码:
try
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string csvPath = openFileDialog1.FileName;
string rowValue;
// int rowValue = int.Parse(??);
string[] cellValue;
dataGridView1.Rows.Clear();
//dataGridView1.Columns.Clear();
if (System.IO.File.Exists(csvPath))
{
System.IO.StreamReader fileReader = new StreamReader(csvPath);
rowValue = fileReader.ReadLine();
cellValue = rowValue.Split(',');
for (int i = 0; i <= cellValue.Count() - 1; i++)
{
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.Name = cellValue[i]; //column name , value
column.HeaderText = cellValue[i];
dataGridView1.Columns.Add(column);
// dataGridView1.Columns[].CellType = typeof(Int64);
}
while (fileReader.Peek() != -1)
{
rowValue = fileReader.ReadLine();
cellValue = rowValue.Split(',');
dataGridView1.Rows.Add(cellValue);
}
fileReader.Dispose();
fileReader.Close();
}
else
尝试在DataGridView
中注册一个比较器,如下所示:
private void CustomSortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
if(e.Column.Name != "CollumnName") return;
var a = int.Parse(e.CellValue1.ToString());
var b = int.Parse(e.CellValue2.ToString());
// If the cell value is already an integer, just cast it instead of parsing
e.SortResult = a.CompareTo(b);
e.Handled = true;
}
并在DataGridView
中注册分类器
dataGridView1.SortCompare += CustomSortCompare;
请参阅文档DataGridView.SortCompare事件
您可以使用此代码以字符串模式检测数字列,将它们转换为整数并排序:
try {
if (e.Column.Index == 2) {
e.SortResult = Convert.ToInt32(e.CellValue1) < Convert.ToInt32(e.CellValue2) ? -1 : 1;
e.Handled = true;
}
} catch (Exception ex) {
}
在上面的示例中,数字位于Datagridview的第2列。将代码放入网格的SortCompare事件中。