Wednesday, March 8, 2006

Sorting DataTables in .NET (C#)

What is the easiest way to sort a DataTable in .NET? Use the DefaultView of the DataTable, and you will find the Sort-property.

Use it like this:

if (sortExpression != null && sortExpression.Length > 0)
table.DefaultView.Sort = sortExpression + " " + sortOrder;
}

If you would like to sort data in a control you could do it like this:

if (this.DataSource is DataTable) {
DataTable table = (DataTable)this.DataSource;
if (sortExpression != null && sortExpression.Length > 0) {
table.DefaultView.Sort = sortExpression + " " + sortOrder;
}
}