Home  »  Articles  »  C#.Net  »

Convert DataTable to DataView and DataView to DataTable in C#.Net

 Posted By : Manoranjan SahooPosted Date : 25/10/2012 06:40:57 AM Category : C#.Net Points : 5

Convert DataTable to DataView and DataView to DataTable :
In this article i am going to show you how to convert DataTable to DataView and vice versa and also how to sort DataTable using DataView sort method.
1. Convert DataTable to DataView :
We can convert DataTable to DataView using DataView constructor DataView(DataTable); Use below code to do so:

DataView ConvertToDataView(DataTable dt)
{
DataView dv = new DataView(dt);
return dv;
}

2. Convert DataView to DataTable :
We can convert DataView to DataTable using DataView's ToTable() method ; Use below code to do so:

DataTable ConvertToDataTable(DataView dv)
{
DataTable dt = new DataTable();
dt=dv.ToTable();
return dt;
}

3. How to Sort DataTable using DataView's Sort property:
See below code how it works :

DataTable ConvertToSortedDataView(DataTable dt)
{
DataView dv = new DataView(dt);
dv.Sort = "Column1 ASC";
return dv.ToTable();
}

Here I want to sort the datatable according to Column1 and it will be in ascending order. So i set Sort property to "Column1 ASC". If i need in descending order then i need to set as "Column1 DESC".

If we need to sort with multiple columns then we need to put those column names with ',' comma separator. See below :

dv.Sort = "Column1,Column2 ASC";

 

Responses
No responses found for this thread. Be the first to respond this thread.
Post Reply
Login to post Response.