Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Populate a DataTable from a Stored Procedure [duplicate]

Tags:

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")); 
like image 933
Rash Avatar asked Nov 15 '12 16:11

Rash


1 Answers

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.

like image 102
Tim Schmelter Avatar answered Oct 17 '22 07:10

Tim Schmelter