Sunday, 25 August 2013

Convert DataReader to DataTable in C#


This example will show how we convert DataReader to DataTable.
To convert DataReader to DataTable we need to use Load() Method.

C# Code 

protected void BindGridview()
{
       using (SqlConnection con = new SqlConnection("Data Source=PERSONAL\SQLEXPRESS;          Integrated Security=true;Initial Catalog=MyTestDb"))
      {
       con.Open();
       SqlCommand cmd = new SqlCommand("Select Name,State,City,ContactNo FROM UserInfo", con);
       SqlDataReader dr = cmd.ExecuteReader();
       DataTable dt=new DataTable();
      dt.Load(dr);
      gvUserInfo.DataSource = dt;
      gvUserInfo.DataBind();
      con.Close();
     }
}