-1

I have some columns in my dataTable viewed by a DatagridView which contain some integer cells(positive or negative) and some cells that their values cannot be converted to integer. Such as, empty cells. How can I sort such a column data. I have tried

     dataTable.Columns.Add("ID", typeof(int));

But this code will give an error since some cell values cannot be converted to an integer.

In short, I need to ignore strings while ordering numerically.

utdlegend
  • 43
  • 1
  • 3
  • 11
  • 1
    So how should all of the non-numeric values be ordered with respect to each other, and how should a numeric and non-numeric value be ordered with respect to each other? – Servy Jan 10 '18 at 19:11
  • non-numeric values can be thrown to the top or bottom of the column while ordering numerically. That will be enough for me, I do not need them ordered alphabetically – utdlegend Jan 10 '18 at 19:13
  • If a NaturalSort doesnt work for you (ignore *alpha* chars), you can provide your own sorter for the column – Ňɏssa Pøngjǣrdenlarp Jan 10 '18 at 19:22

1 Answers1

-1

You must compare using the object type rather than a specific type, and create a custom comparison function.

Ex:

int Compare(object a, object b)
{
    if (a is string && b is string)
    { 
        return ((string)a).CompareTo((string)b);
    }
    if (a is int && b is int)
    {
        return ((int)a).CompareTo((int)b);
    }
    else
    {
        //Maybe here you also would throw an error if a or b was 
        //an unexpected type like DateTime

        return a.ToString().CompareTo(b.ToString());
    }
}

Then sort the grid or list using this comparison.

The implementation is probably going to be more complicated than what I have written to seem natural to users.

See Natural Sort Order in C#

JamesFaix
  • 8,050
  • 9
  • 37
  • 73
  • The OP is not clear whether they are talking about one column or more than one. If it is one column containing numerals and alpha characters, the DataColumn would be string - the DGV is not going to know how to parse or format `Object`. Also, a Natural Sorter wont work with the requirement to *ignore strings* (which I take to mean ignore alpha characters) – Ňɏssa Pøngjǣrdenlarp Jan 10 '18 at 19:30