Change datatable and tableadapter schema at runtime according to stored procedure. C#
I have DataSet and TableAdapter for the table in that DataSet. The problem is that TableAdapter uses a stored procedure to fill DataTable, but the amount of returned columns can be different. How can I change the 开发者_运维问答schema of DataTable at runtime to get all the columns from stored procedure?
In my opinion, drop the idea of using the DataAdapter, it's completely unnecessary. Do this to get the DataTable instead:
using(SqlConnection con = new SqlConnection("Conectionstring"))
{
con.Open();
using (SqlCommand commnand= new SqlCommand("StoredProcName",con))
{
command.CommandType=CommandType.StoredProcedure;
SqlDataReader reader = command.ExecuteReader();
DataTable table = new DataTable();
table.Load(reader);
return table;
}
}
Now it doesn't matter the # of columns you return from the proc, the datatable will contain all of them.
EDIT: Add the following section to your Web.config file below the <configuration>
section replacing the actual connectionString for yours. You should be able to copy this from the Your Settings file.
And now create your SqlConnection as follows:
SqlConnection con
= new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
Notice that "ConnectionString" is the name attribute of the connection string in the Web.Config.
See another example here, in case is not very clear.
精彩评论