|
Convert DataView To DataTable
.Net framework has a very useful class DataView that lets us
create desired view from a given DataTable by specifying some row
filtering expression or some sorting expression. And then we bind this view to
some databound control. Then we look for some way to get the filtered view as a
DataTable. This very useful feature is missing in DataView class.
In this article we will try to fill the gap by providing a utility method that
takes a DataView object and converts into a DataTable
preserving the filter and sorting that you applied to the original DataTable.
public static DataTable CreateTable(DataView obDataView)
{
if (null == obDataView)
{
throw new ArgumentNullException
("DataView", "Invalid DataView object specified");
}
DataTable obNewDt = obDataView.Table.Clone();
int idx = 0;
string [] strColNames = new string[obNewDt.Columns.Count];
foreach (DataColumn col in obNewDt.Columns)
{
strColNames[idx++] = col.ColumnName;
}
IEnumerator viewEnumerator = obDataView.GetEnumerator();
while (viewEnumerator.MoveNext())
{
DataRowView drv = (DataRowView)viewEnumerator.Current;
DataRow dr = obNewDt.NewRow();
try
{
foreach (string strName in strColNames)
{
dr[strName] = drv[strName];
}
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
obNewDt.Rows.Add(dr);
}
return obNewDt;
}
|