Search code examples
c#stringcsvdatagridviewint

Sorting numeric strings


I'm using DatagridView in to read a csv file.
The data is not sorting properly when clicking the headers at the top of the grid.

For example, it should be sorted as 1,2,3,4,5,etc
However, the result is 1,10,2,20,etc.

I think I need to convert it from a string to an int, but I don't know how to do that.

Here's my current code:

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

Solution

  • Try to register a comparer into the DataGridView like this:

    private void CustomSortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
        if(e.Column.Name != "ColumnName") 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;
    }
    

    and the register the sorter in the DataGridView

    dataGridView1.SortCompare += CustomSortCompare;
    

    See the documentation DataGridView.SortCompare Event