In this post, I will show you a simple trick that converts DataReader
to DateSet
easily, Checkout the following code snippet.
static DataSet DataReaderToDataSet(IDataReader reader)
{
DataTable table = new DataTable();
int fieldCount = reader.FieldCount;
for (int i = 0; i < fieldCount; i++)
{
table.Columns.Add(reader.GetName(i), reader.GetFieldType(i));
}
table.BeginLoadData();
object[] values = new object[fieldCount];
while (reader.Read())
{
reader.GetValues(values);
table.LoadDataRow(values, true);
}
table.EndLoadData();
DataSet ds = new DataSet();
ds.Tables.Add(table);
return ds;
}
public static DataSet DataReaderToDataSet2()
{
using (SqlConnection connection = new
SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
string Query = @"SELECT * From addressbook";
SqlCommand command = new SqlCommand(Query, connection);
command.CommandType = CommandType.Text;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
DataTable myTable = new DataTable("myTable");
myTable.Columns.Add("FirstName", typeof(string));
myTable.Columns.Add("LastName", typeof(string));
myTable.Columns.Add("Email", typeof(string));
while (reader.Read())
{
myTable.Rows.Add(new object[] {reader["FirstName"].ToString(),
reader["LastName"].ToString(),
reader["Email"].ToString()});
}
myTable.AcceptChanges();
DataSet ds = new DataSet();
ds.Tables.Add(myTable);
ds.AcceptChanges();
return ds;
}
}
public static DataTable DataReaderToDataSet3(IDataReader reader)
{
DataTable orders = new DataTable("Orders");
orders.Load(reader);
}