How to sort string as numbers in DataGridView

前端 未结 1 848
小鲜肉
小鲜肉 2021-01-28 03:51

I have string column with specific numbers in a datagridview. It\'s not bound. I would like to sort it correctly. Default DataGridView sorting doesn\'t sort it correct.

相关标签:
1条回答
  • 2021-01-28 04:41

    As you have stated you are not using a DataSource then you could try using the SortCompare event.

    This event will be called when the user clicks a column to change the sort order, or when you programatically call the Sort function.

    Here is a basic example. I am making assumptions that you want to sort be year(?) then month(?) then the first number:

    private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
    
        // Check if we are sorting by the special column.
        if (myDataGridView.Columns.Contains("My_Column") && e.Column == myDataGridView.Columns["My_Column"])
        {
    
            // Parse the special values (add validation if required).
            string[] parts1 = e.CellValue1.ToString().Trim().Split('/');
            int a1 = int.Parse(parts1[0].Split(' ')[2]);
            int b1 = int.Parse(parts1[1]);
            int c1 = int.Parse(parts1[2]);
            string[] parts2 = e.CellValue2.ToString().Trim().Split('/');
            int a2 = int.Parse(parts2[0].Split(' ')[2]);
            int b2 = int.Parse(parts2[1]);
            int c2 = int.Parse(parts2[2]);
    
            // Compare each value as required.
    
            // First compare the last value (year?)
            e.SortResult = c1.CompareTo(c2);
    
            // If equal, then compare second value (month?)
            if(e.SortResult == 0)
                e.SortResult = b1.CompareTo(b2);
    
            // Finally if still equal, then compare first value
            if(e.SortResult == 0)
                e.SortResult = a1.CompareTo(a2);
    
        }
    
    }
    

    NOTE: If you cannot ensure you will always have a valid format in every cell, then you will need to add validation logic to this event. For example, use int.TryParse() and check for null values, and validate the length of the string splits.

    0 讨论(0)
提交回复
热议问题