根据存储过程在运行时更改datatable和tableadapter模式.c#



我有DataSet和TableAdapter表在该数据集。问题是,TableAdapter使用一个存储过程来填充DataTable,但是返回的列的数量可能不同。如何在运行时更改DataTable的模式以从存储过程中获取所有列?

在我看来,放弃使用DataAdapter的想法,这是完全不必要的。执行以下操作来获取DataTable:

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;
    }
}

现在,从进程返回的列数已经不重要了,数据表将包含所有列。

编辑:将以下部分添加到您的Web。<configuration>节下面的配置文件替换实际的connectionString为您的。你应该可以从你的设置文件中复制这个。

现在按如下方式创建SqlConnection:

SqlConnection con 
= new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))

注意,"ConnectionString"是Web.Config中连接字符串的名称属性。

如果不是很清楚,请参阅这里的另一个示例

最新更新