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 4616674
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T02:00:59+00:00 2026-05-22T02:00:59+00:00

I have a DataGridView which is data-bound to a BindingList. My DataGridView also has

  • 0

I have a DataGridView which is data-bound to a BindingList. My DataGridView also has a couple of custom columns that I have added. These are not data-bound, but rather are generated based on items in my BindingList (ie: an item in my BindingList of type A has a property of type B; my custom column shows B.Name (EDIT: In this case, “Name” is a property of the class B, and thus the property represented by the column is not directly found in the items in the BindingList)).

I need to be able to sort all of the columns in my DataGridView. DataGridView has two sort methods: Sort(IComparer), and Sort(DataGridViewColumn, ListSortDirection). I use the second one to sort my data-bound columns, but it of course throws an exception when used on a non-data-bound column. The first method will throw an exception if DataSource is not null.

So neither of DataGridView’s built-in Sort methods will work as far as I can tell. How else can I sort my grid based on my custom columns?

EDIT:

What I do at the moment is handle the click on the column header, following the instructions seen here: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columnheadermouseclick.aspx

The problem arises on the line:

dataGridView1.Sort(newColumn, direction);

Things work great when newColumn holds one of the properties of an object in my BindingList. But in order to sort one of my custom columns, I will have to avoid this line altogether, and find some other way to sort the data grid based on that column. Does that mean having to build my own sort function? That seems like it may be a humongous pain.

  • 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-05-22T02:01:00+00:00Added an answer on May 22, 2026 at 2:01 am

    FINAL Edit/Answer: I can’t think of a way to do this while still using the sorting mechanism built into the DataGridView. If I were in your shoes, I would probably just change the SortMode of each column to “Programmatic” and then handle the “ColumnHeaderMouseClick” yourself. At that point you should call a sort method in your modified BindingList class which will perform the sorting as necessary according the which column was clicked. This avoids using the Sort method of the DGV and sorts the underlying list directly.

    Full Discourse Located in the comments section. Original Answer follows immediately:

    EDIT: Due to some confusion about the problem and subsequent discussion about it, I have a new suggestion down in the comments of this Answer. I’m leaving the original answer I posted so that we can reference it.

    I recently had to do this – and I won’t lie it was a real pain. I did come up with a solution (with help from some friends here at SO) so here goes. I created a new IComparer based interface that allows you to specify both a column and a direction. I only did this because I need my sorting code to be as generic as possible – I have TWO grids that need to sort like this, and I don’t want to maintain twice the code. Here is the interface, quite simple:

       public interface IByColumnComparer : IComparer
       {
          string SortColumn { get; set; }
          bool SortDescending { get; set; }
       }
    

    Obviously, if you’re not worried about keeping things generic (you probably should) than this isn’t strictly necessary. Then, I built a new class that is based on BindingList<>. This allowed me to override the sorting code and provide my own IByColumnComparer on a column by column basis which is what allowed for the flexibility I needed. Check this out:

    public class SortableGenericCollection<T> : BindingList<T>
    {
      IByColumnComparer GenericComparer = null; 
    
      public SortableGenericCollection(IByColumnComparer SortingComparer)
      {
         GenericComparer = SortingComparer;
      }
    
    
      protected override bool SupportsSortingCore
      {
         get
         {
            return true;
         }
      }
    
      protected override bool IsSortedCore
      {
         get
         {
            for (int i = 0; i < Items.Count - 1; ++i)
            {
               T lhs = Items[i];
               T rhs = Items[i + 1];
               PropertyDescriptor property = SortPropertyCore;
               if (property != null)
               {
                  object lhsValue = lhs == null ? null :
                  property.GetValue(lhs);
                  object rhsValue = rhs == null ? null :
                  property.GetValue(rhs);
                  int result;
                  if (lhsValue == null)
                  {
                     result = -1;
                  }
                  else if (rhsValue == null)
                  {
                     result = 1;
                  }
                  else
                  {
                     result = GenericComparer.Compare(lhs, rhs); 
                  }
                  if (result >= 0)
                  {
                     return false;
                  }
               }
            }
            return true;
         }
      }
    
      private ListSortDirection sortDirection;
      protected override ListSortDirection SortDirectionCore
      {
         get
         {
            return sortDirection;
         }
      }
    
      private PropertyDescriptor sortProperty;
      protected override PropertyDescriptor SortPropertyCore
      {
         get
         {
            return sortProperty;
         }
      }
    
      protected override void ApplySortCore(PropertyDescriptor prop,
      ListSortDirection direction)
      {
         sortProperty = prop;
         sortDirection = direction;
    
         GenericComparer.SortColumn = prop.Name;
         GenericComparer.SortDescending = direction == ListSortDirection.Descending ? true : false;
    
         List<T> list = (List<T>)Items;
         list.Sort(delegate(T lhs, T rhs)
         {
            if (sortProperty != null)
            {
               object lhsValue = lhs == null ? null :
               sortProperty.GetValue(lhs);
               object rhsValue = rhs == null ? null :
               sortProperty.GetValue(rhs);
               int result;
               if (lhsValue == null)
               {
                  result = -1;
               }
               else if (rhsValue == null)
               {
                  result = 1;
               }
               else
               {
                  result = GenericComparer.Compare(lhs, rhs);
               }
               return result;
            }
            else
            {
               return 0;
            }
         });
      }
    
      protected override void RemoveSortCore()
      {
         sortDirection = ListSortDirection.Ascending;
         sortProperty = null;
      }
    }
    

    Now, as you can see in the ApplySortCore method, I am receiving the column and the direction directly from the DataGridView – meaning that I am not calling this programmatically. That doesn’t sound like what you want to do, but you could easily modify this code if you need to call it programmatically and pass the appropriate IByColumnComparer. My point in showing you all this is so you can understand how to modify the sorting algorithm, which is quite useful.

    Special thanks to @MartinhoFernandes for the suggestions concerning making this class more generic.

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

Sidebar

Related Questions

I have a datagridview where the users can select which subset of columns to
I have a BindingList which is the data source for a Bindingsource, which in
I have a DataGridView being regularly populated via data-bound objects, and the number of
I have a list of objects (of type 'TrackedSet') that is data bound to
I have a DataGridView bound to a bindingsource which is bound to a List<T>
I have a datagridview which im binding DataTable to. What I want do is
Say I have a DataGridView in which I dynamically build up a ComboBox column
I currently have a functioning in-house Windows Forms application which extensively uses the DataGridView
I have a DataGridView with its datasource set to a generic list of custom
I have a DataGridView that I want to query using Linq (C# WinForm). I

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.