排序数字字符串

时间:2015-12-17 02:07:19

标签: c# string csv datagridview int

我在中使用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

2 个答案:

答案 0 :(得分:0)

尝试将比较器注册到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 Event

答案 1 :(得分:0)

您可以使用此代码检测字符串模式中的数字列,将它们转换为整数并对它们进行排序:

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事件中。