Possible Duplicate:
How can i retrieve a table from stored procedure to a datatable
I am trying to populate my datatable. I have created a datatable tmpABCD but i need to populate this with the values from a stored procedure. I am not able to proceed further.
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString); sqlcon.Open(); SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon); DataTable dt = new DataTable("tmpABCD"); dt.Columns.Add(new DataColumn("A")); dt.Columns.Add(new DataColumn("B")); dt.Columns.Add(new DataColumn("C")); dt.Columns.Add(new DataColumn("D"));
You don't need to add the columns manually. Just use a DataAdapter
and it's simple as:
DataTable table = new DataTable(); using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString)) using(var cmd = new SqlCommand("usp_GetABCD", con)) using(var da = new SqlDataAdapter(cmd)) { cmd.CommandType = CommandType.StoredProcedure; da.Fill(table); }
Note that you even don't need to open/close the connection. That will be done implicitly by the DataAdapter
.
The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With