Sort DataTable

  • Thread starter Thread starter Necqui Teja
  • Start date Start date
N

Necqui Teja

I have UPC and ItemNo as columns in my DataTable dt.

How do I sort the columns in my method prior to return dt;

I tried the following but it doesn't seem to work.

dt.DefaultView.Sort = "UPC ASC";
return dt;

Necqui
 
You're sorting the DefaultView not the DataTable. If you set a datagrid to
DataTable.DefaultView you should see the records are sorted.

-Joe
 
The sort is of the DataView, not the DataTable.
So for example if you were to assign the DefaultView (DataView) as the
DataSource of a DataGrid control, you would see the sort results. The
original DataTable will remain unchanged.
Peter
 
Hi,

A datatable is not sortable itself, what you do is using one or more
DataView of the same table, in each DataView you can set the sort order as
needed.
 
How can I take a sorted DataView and move it to a new DataTable so that I
can iterate using the foreach loop? I'm not using DataSource/DataGrid in my
application.

Necqui
 
Don't iterate over the DataTable; iterate over the DataView.

DataTables are always in the order in which rows were returned by the
data source. (Your other choice is to request the rows from your data
source in the order you want them.)

However, it's better to just iterate over the DataView rather than the
DataTable. Then you can have any sorting order you want.
 
Hi,

Necqui Teja said:
How can I take a sorted DataView and move it to a new DataTable so that I
can iterate using the foreach loop? I'm not using DataSource/DataGrid in
my application.

You can iterate in the dataview:

foreach( DataRowView row in theView )
dosomethigwith( row)

you can access the row using DataRowView.Row , so if you have a method that
especificaly use a Row you can use

foreach( DataRowView row in theView )
dosomethigwith( row.Row )


In general all list controls (Datagrid, listview, etc ) can handle DataView
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top