Populating DataView from DataReader
Introduction:
This article will illustrate how
to populate DataView from DataReader in C#. In many scenarios we may have the
data in DataReader which is required to be bind to GridView or some other
control. In this scenario we can populate a DataView from DataReader and then
provide the populated DataView to our Control.
Code Snippet:
For ease I am creating a function
that will take a DataReader (or IDataReader) and Table Name as parameter and returns
a populated DataView.
private DataView PopulateDataView(IDataReader
dataReader, string tableName)
{
DataTable
dataReaderTable = new DataTable(tableName);
try
{
for
(int count = 0; count <
dataReader.FieldCount; count++)
{
DataColumn
tempCol = new DataColumn(dataReader.GetName(count),
dataReader.GetFieldType(count));
dataReaderTable.Columns.Add(tempCol);
}
while
(dataReader.Read())
{
DataRow
dr = dataReaderTable.NewRow();
for
(int i = 0; i < dataReader.FieldCount; i++)
{
dr[i] =
dataReader.GetValue(dataReader.GetOrdinal(dataReader.GetName(i)));
}
dataReaderTable.Rows.Add(dr);
}
return
dataReaderTable.DefaultView;
}
catch
{
return
null;
}
}
Explanation:
Please find the explanation of
the code listed above as under.
1. At
the beginning of the method, we created an instance of temporary DataTable
named 'dataReaderTable' by passing in the table name to it.
2. We
defined the columns of the 'dataReaderTable' by iterating through the
DataReader for retrieving Column name and its DataType.
3. We
iterated through the DataReader and inserted the data from it into DataTable
using a DataRow.
4. To
return DataView from the method, dataReaderTable.DefaultView is returned.
5. Whole
of the code block is inserted into a Try and a Catch block. In case any exception
is generated then null is returned from the method.
Conclusion:
With this method we need not to
populate the DataSet so as to provide it as a datasource to a binding control. We
can also use the DataReader and fill DataView with it and use this Dataview as
a source for a binding control.