Subscribe to
Posts
Comments

Sorting a DataTable

Normally if you were trying to sort a DataTable you would do see something like

DataTable table = retrieveTable();
DataView view = new DataView(table);
view.Sort = "Name";
datagrid1.DataSource = view;
datagrid1.DataBind();

Doing this works fine for UI cases, but if you need to get access to the sorted table you’ll want to do this.

DataTable unsortedTable = retrieveTable();
DataTable sortedTable = new DataTable();
foreach (DataRow row in unsortedTable.Select(string.Empty, "Name")) {
	sortedTable.ImportRow(row);
}

And then you can mess with your sortedTable object.