How to Convert SqlDataReader object to DataTable in C#, ADO.Net?
This is a very simple tip which will help us to convert an ADO.Net SqlDataReader object to DataTable object in C#.
The Load(DataReader) method packed with the DataTable object will do the trick for us.
Refer the below code where the datareader object is passed to Load method of DataTable.
public DataTable GetData() { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); SqlCommand com = new SqlCommand("SELECT [emp_id], [fname], [lname], [job_id], [hire_date] FROM [employee] ORDER BY [emp_id], [fname]", con); DataTable dt = new DataTable(); SqlDataReader dr = com.ExecuteReader(); dt.Load(dr); return dt; }
Include System.Data and System.Data.SqlClient namespace for the above code to work.
Happy Coding!!
|