Showing posts with label DataTable. Show all posts
Showing posts with label DataTable. Show all posts

Tuesday, August 24, 2010

Converting DataView To DataTable

We oftenly need to convert DataView to DataTable during development. Here I have created a generic function to convert a DataView object to DataTable object. You have to just call this function to get DataTable object of DataView object.


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 { }
obNewDt.Rows.Add(dr);
}
return obNewDt;
}


Happy Coding...