Sangram Nandkhile
Sangram Nandkhile

Reputation: 18192

Sorting Datarows using any dataColumn

I have a following datatable with 3 columns.

enter image description here

I want to sort the datatable rows on the basis of 2nd column.(with header E) Is there any built in function do this?

i tried..

    dt.DefaultView.Sort = dt.Columns[1].ColumnName;
    dt.AcceptChanges();

Upvotes: 3

Views: 19278

Answers (2)

HatSoft
HatSoft

Reputation: 11191

You can sort a datable by column

 dt.DefaultView.Sort = "E Asc";

Else this way

string[] names = new string[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
    names[i] = dt.Rows[i]["E"].ToString();
}
Array.Sort(names);

for (int i = 0; i < dt.Rows.Count; i++)
{
    dt.Rows[i]["E"] = names[i];
}

Also dt.AcceptChanges will commits all the changes made to the table. aah msdn also say that it must be called after attempt to update is made

Remarks from MSDN

When AcceptChanges is called, any DataRow object still in edit mode successfully ends its edits. The DataRowState also changes: all Added and Modified rows become Unchanged, and Deleted rows are removed.

The AcceptChanges method is generally called on a DataTable after you attempt to update the DataSet using the DbDataAdapter.Update method.

Upvotes: 4

Tim Schmelter
Tim Schmelter

Reputation: 460058

Probably the easiest (and most powerful) way is to use Linq-To-DataSet and Enumerable.OrderBy:

var tblOrdered = tbl.AsEnumerable()
                    .OrderBy(row => row.Field<int>("E"))
                    .CopyToDataTable();

If you cannot use Linq, you can use DataView.Sort:

DataView view = tbl.DefaultView;
view.Sort = "E ASC";

But that uses a DataView, the original DataTable is unsorted.

So if you need the table, you could use DataView.ToTable:

tbl = view.ToTable();

Upvotes: 7

Related Questions