Sorting a DataTable

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

[csharp]
DataTable table = retrieveTable();
DataView view = new DataView(table);
view.Sort = “Name”;
datagrid1.DataSource = view;
datagrid1.DataBind();
[/csharp]

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

[csharp]
DataTable unsortedTable = retrieveTable();
DataTable sortedTable = new DataTable();
foreach (DataRow row in unsortedTable.Select(string.Empty, “Name”)) {
sortedTable.ImportRow(row);
}
[/csharp]

And then you can mess with your sortedTable object.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s