1

This is a C# Winform question. I have a DataGridView which is bounded to a DataTable. I construct the DataTable myself, which several DataColumn instances. When the DataTable is bound to the DataGridView, by default, every column is sortable by clicking the headers of the DataGridView.

But the sorting behavior is something "by default". It seems that it is sorted by string. This is true even if I put this as my code:

DataColumn dc = new DataColumn("MyObjectColumn", typeof(MyObject));

And MyObject has overriden ToString() and has implemented the IComparable interface. That means even if I have told the DataTable how to sort the special column with the implementation of IComparable interface, DataGridView still doesn't do it the way I expect.

So how can I let DataTable sort data in the way I want?

Thanks for the answers.

Steve
  • 4,935
  • 11
  • 56
  • 83

2 Answers2

2

I would recommend using the DefaultView of the DataTable. It has some built in sorting features that are little more extendable. The easiest is RowFilter, but I'm not sure if this will be what you're looking for if your data types are overridden as .ToString() at the table level.

EDIT: added code snippet

A custom method like this that maybe even overrides or is called during the sort event of your DataGridView might be able to sort a DataView before the binding actually occurs. But as I understand it, the IComparable never gets called unless you specify it to be called.

protected void SortGrid()
{
    System.Data.DataView dv = myDataTable.DefaultView;

    myOjbect comparer = new MyObject();

   // Comparer specifics go here. Sort order, column/fieldname etc
   // or any custom properties used in sorting

   dv.Sort(comparer)

   dgMyGrid.DataSource = dv
   dgMyGrid.DataBind()

}
Joel Etherton
  • 37,325
  • 10
  • 89
  • 104
0

I had to deal with this today. I've implemented a natural sort (hat tip: Natural Sort Order in C#) and had to sort a DataTable. This is more of a "low fi" method, but it did the trick for the small dataset I'm working with.

I'm creating a key/value value relationship between my sorting column, and the DataRow itself, and popping it into a SortedList constructed with an IComparer.

DataTable myDataTable = {all my data...}
SortedList myDataNaturallySorted = new SortedList(new NaturalComparer());

foreach (DataRow dataRow in myDataTable.AsEnumerable())
    myDataNaturallySorted.Add(dataRow["columWithKeyName"].ToString(), dataRow);

Then I moved forward using the sorted list as a data source for my repeater.

Community
  • 1
  • 1
ThisGuyKnowsCode
  • 530
  • 4
  • 18