I was writing an application to read data from AS 400, Db2, based on the data I have to generate a report. I was trying to covert OdbcDataReader to DataSet. The following Code was helpful to do the same... We can use it for SqlDataReader as well.
Code:
public DataSet ConvertDataReaderToDataSet(System.Data.Odbc.OdbcDataReader reader)
{
DataSet dataSet = new DataSet();
do
{
// Create data table in runtime
DataTable schemaTable = reader.GetSchemaTable();
DataTable dataTable = new DataTable();
if (schemaTable != null)
{
for (int i = 0; i < schemaTable.Rows.Count; i++)
{
DataRow dataRow = schemaTable.Rows[i];
// Create a column name as provided in Schema
string columnName = (string)dataRow["ColumnName"];
// Define Column Type here
DataColumn column = new DataColumn(columnName, (Type)dataRow["DataType"]);
//Adding Column to table
dataTable.Columns.Add(column);
}
dataSet.Tables.Add(dataTable);
// Fill the data table from reader data
while (reader.Read())
{
DataRow dataRow = dataTable.NewRow();
for (int i = 0; i < reader.FieldCount; i++)
dataRow[i] = reader.GetValue(i);
dataTable.Rows.Add(dataRow);
}
}
else
{
// No records were returned
DataColumn column = new DataColumn("RowsAffected");
dataTable.Columns.Add(column);
dataSet.Tables.Add(dataTable);
DataRow dataRow = dataTable.NewRow();
dataRow[0] = reader.RecordsAffected;
dataTable.Rows.Add(dataRow);
}
}
while (reader.NextResult());
return dataSet;
}
Hope It Helpzzzz
4ZZZZ