Steve Holstad's "the bright lights"

"Just because your voice reaches halfway around the world doesn't mean you are wiser than when it reached only to the end of the bar." - Edward R. Murrow
in

Sort a datatable before binding using DefaultView

Here's a quick solution I found that may save you a few minutes...

I needed to sort a datatable of records, which normally would be handled by my stored procedure, however in this case the data had been delivered from a hashtable:

Instead of using the datatable's Select statement to produce an array of DataRows, you can use the DefaultView of the datatable to handle sorting for you; much quicker and more efficient than repopulating another datatable:

// currentTable is a datatable of non-sorted rows
DataSet dsSorted = new DataSet();
private const string Sort_Column_Key = "myColumn";
private const string Sort_Direction = " DESC";
private const string Sort_Format = "{0} {1}";

// Sort by our sort column, in Sort_Direction order
currentTable.DefaultView.Sort = string.Format(Sort_Format, Sort_Column_Key, Sort_Direction);

// Add sorted table to dataset, then bind to control
// NOTE the use of ToTable to produce a datatable from our sorted view        
dsSorted.Tables.Add(currentTable.DefaultView.ToTable());
gridView1.DataSource = dsSorted;
gridView1.DataBind();

Comments

No Comments