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 bound 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.

Example. 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 below.

  1. At the beginning of the method, we created an instance of a temporary DataTable named 'dataReaderTable' by passing the table name to it.
  2. We defined the columns of the 'dataReaderTable' by iterating through the DataReader to retrieve the Column name and its data type.
  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. The 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 Data so as to provide it as a data source 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.


Similar Articles