Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8192509
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T04:11:50+00:00 2026-06-07T04:11:50+00:00

I have a DataGridView and I need to use a custom sorter (derived from

  • 0

I have a DataGridView and I need to use a custom sorter (derived from System.Collections.IComparer). That was working fine, but I noticed that I hadn’t quite gotten my comparisons right because it ends up doing a string compare on the cells regardless of their underlying data type. (so, 1, 10, 2) instead of (1, 2, 10).

How can I write a compare function that could appropriately compare columns regardless of their data type?

public int compare(object x, object y)
{
    DataGridViewRow dr1 = (DataGridViewRow)x;
    DataGridViewRow dr2 = (DataGridViewRow)y;

    object cell1 = dr1.Cells["SomeName"].Value;
    object cell2 = dr2.Cells["SomeName"].Value;

    //Compare cell1 and cell 2 based on the data type in
    //dr1.Cells["SomeName"].ValueType.
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T04:11:51+00:00Added an answer on June 7, 2026 at 4:11 am

    It seems that there a couple of essential parts to any solution to this problem.

    1. Ensure you are comparing like types.
    2. Ensure that you can compare instances of the type.

    Here are some ideas to get you started. I’ve omitted some error checking in the interest of clarity.

    Assume:

    Type type1 = dr1.Cells["SomeName"].ValueType;
    Type type2 = dr2.Cells["SomeName"].ValueType;
    

    Then see if you can coerce one value to the other’s type:

    if (type1 != type2)
    {
        TypeConverter tc1 = TypeDescriptor.GetConverter(type1);
        TypeConverter tc2 = TypeDescriptor.GetConverter(type2);
    
        if (tc1.CanConvertFrom(type2))
        {
            cell2 = tc1.ConvertFrom(cell2);
            type2 = type1;
        }
        else if (tc1.CanConvertTo(type2))
        { 
            cell1 = tc1.ConvertTo(cell1, type2);
            type1 = type2;
        }
        else if (tc2.CanConvertFrom(type1))
        {
            cell1 = tc2.ConvertFrom(cell1);
            type1 = type2;
        }
        else if (tc2.CanConvertTo(type1))
        { 
            cell2 = tc2.ConvertTo(cell2, type1);
            type2 = type1;
        }
        else // fallback to string comparison
        {
            cell1 = tc1.ConvertToString(cell1);        
            type1 = cell1.GetType();
    
            cell2 = tc2.ConvertToString(cell2);        
            type2 = cell2.GetType();
        }
        // cell1 and cell2 should be the same type now
    }
    

    Now that you have instances of like type, you need to find a way to compare them.

    If you are using C# 4, then the dynamic keyword may be your friend:

    dynamic c1 = cell1;
    try 
    {
        int compareResult = c1.CompareTo(cell2);
    }
    catch(Exception)
    {
        // type1 doesn't implement an IComparable-like interface
    }
    

    If you aren’t using C# 4, you can see if the values implement IComparable:

    if (cell1 is IComparable)
    {
       int compareResult = ((IComparable)cell1).CompareTo(cell2);
    }
    

    Or perhaps it implements a generic IComparable<T>, in which case may need to resort to some reflection trickery:

    Type genericComparableType = typeof(IComparable<>);
    Type typedComparableType = genericComparableType.MakeGenericType(new Type[] { type1 });
    if (typedComparableType.IsInstanceOfType(cell1))
    {
        MethodInfo compareTo = typedComparableType.GetMethod("CompareTo", new Type[] { type1 });
        int compareResult = (int)compareTo.Invoke(cell1, new object[] { cell2 });
    }
    

    Finally, you can see if Comparer<T>.Default will work, again using some reflection:

    Type genericComparerType = typeof(Comparer<>);
    Type typedComparerType = genericComparerType.MakeGenericType(new Type[] { type1 });
    PropertyInfo defaultProperty = typedComparerType.GetProperty("Default", BindingFlags.Static | BindingFlags.Public);
    
    object defaultComparer = defaultProperty.GetValue(null, null);
    MethodInfo compare = defaultComparer.GetType().GetMethod("Compare", new Type[] { type1, type1 });
    int compareResult = (int)compare.Invoke(defaultComparer, new object[] { cell1, cell2 });
    

    If none of these work, then you will have to fallback to string comparison.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have datagridview with checkbox column, but I want, that some of the columns
I have a Datagridview in my C# program that contain numeric data. I need
I have a DataGridView populated from a database, and I need to take each
I have a datagridview control that where I need to color the rows based
I have a DataGridView with four Columns and need to crate a multiline string
Hi Programmers, Actually I have a DataGridViewComboBoxCell in DataGridvIew and I need to change
I have a dataGrid(not dataGridView) in which i need to add Checkbox dynamically at
Description: I have a problem regarding DataGridView . I need to show a Client_Name
I have a datagridview, and it loads information from db. However, at run time,
I need to have multiple lines in a cell, so I use DataGridViewTextBoxColumn.DefaultCellStyle.WrapMode =DataGridViewTriState.True.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.