Dynamically Parsing Fields/Columns From a DataReader

-------------------------------------------------------
Goto blog home
Visit my new blog dedicated to Internet of Things, Embedded Programming & Automation
-------------------------------------------------------
Today I was faced with a situation where I had to write a data layer function using ADO.NET that would be able to read the resultset from a stored procedure irrespective of number of field/columns and their names. And eventually serialize the stored procedure output for consumption through a web service. Here is the code listing:
-------------------------------------------------------
public DataSet GetDataTableFromReader(string strDataSetName, string strDataTableName, OracleDataReader objReader)
{
DataSet _dsResult = new DataResult(strDataSetName);
DataTable _dtResult = new DataTable(strTableName);
DataRow _dtRow;

DataColumn _dc = new DataColumn();
for (int i = 0; i < objReader.FieldCount; i++)
{
_dc.ColumnName = objReader.GetName(i);
_dtResult.Columns.Add(_dc);
_dc = new DataColumn();
}
if (objReader.HasRows)
{
while (objReader.Read())
{
_dtRow = _dtResult.NewRow();
for (int i = 0; i < objReader.FieldCount; i++)
{
_dtRow[objReader.GetName(i)] = objReader[objReader.GetName(i)];
}
_dtResult.Rows.Add(_dtRow);
}
_dsResult.Tables.Add(_dtResult);
}
_dc.Dispose();
_dtRow = null;
_dtResult.Dispose();
return _dsResult.GetXML();
}