How To Convert DataReader to DataTable and DataSet C#

How To Convert DataReader to DataTable and DataSet C#

Converting DataReader to DataSet using C#

 

using System.Data;
using System.Configuration;
using System.Data.SqlClient;

 

protected void ConvertDataReaderToDataSet(object sender, EventArgs e)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customer"))
        {
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                DataSet dsCustomers = new DataSet();
                dsCustomers.Tables.Add("Customer"); 
                
                dsCustomers.Tables[0].Load(sdr);
            }
            con.Close();
        }
    }
}

 

Converting DataReader to DataTable using C#

 

protected void ConvertDataReaderToDataTable(object sender, EventArgs e)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customer"))
        {
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                DataTable dtCustomers = new DataTable("Customer");
 
                dtCustomers.Load(sdr);
            }
            con.Close();
        }
    }
}

 

2021-10-03