简体   繁体   中英

How to sort string as numbers in DataGridView

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.

Example: Dgv sorts it like this:

 - FS 752/08/2014
 - FS 752/06/2015
 - FS 751/12/2013
 - FS 751/08/2014
 - FS 751/06/2015

And it should be like this:

 - FS 752/06/2015
 - FS 751/06/2015
 - FS 752/08/2014
 - FS 751/08/2014
 - FS 751/12/2013

How can I achieve this?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM