Friday, September 30, 2005

.Net C# howto convert DataReader to Dataset

public DataSet ConvertDataReaderToDataSet(OleDbDataReader reader)
{
DataSet dataSet = new DataSet();
DataTable schemaTable = reader.GetSchemaTable();
DataTable dataTable = new DataTable();

for(int cntr = 0; cntr < schemaTable.Rows.Count; ++cntr )
{
DataRow dataRow = schemaTable.Rows[cntr];
string columnName = dataRow["ColumnName"].ToString();
DataColumn column = new DataColumn(columnName,dataRow.GetType());
dataTable.Columns.Add(column);
}

dataSet.Tables.Add(dataTable);

while (reader.Read())
{
DataRow dataRow = dataTable.NewRow();
for(int cntr = 0; cntr < reader.FieldCount; ++cntr)
{
dataRow[cntr] = reader.GetValue(cntr);
}
}

return dataSet;
}

1 comment:

Anonymous said...

I think you need to using cntr as index for dataRow when calling GetType(). Otherwise the type you return will always be of type DataRow, not the column type.

Modified code is below

for(int cntr = 0; cntr < schemaTable.Rows.Count; ++cntr )
{
DataRow dataRow = schemaTable.Rows[cntr];
string columnName = dataRow["ColumnName"].ToString();
DataColumn column = new DataColumn(columnName,dataRow[cntr].GetType());
dataTable.Columns.Add(column);
}

Shared Cache - .Net Caching made easy

All information about Shared Cache is available here: http://www.sharedcache.com/. Its free and easy to use, we provide all sources at codeplex.

Facebook Badge