[英]How do I convert a DataSet to a DataTable in C#
Here is my code -- I simply need to convert a SQL DataSet into a DataTable in asp.net 4.5. 这是我的代码-我只需要在asp.net 4.5中将SQL DataSet转换为DataTable。 I can't seem to figure it out. 我似乎无法弄清楚。 There are many posts doing the opposite, but none that I can find that clearly answers. 有许多相反的文章,但我找不到能清楚回答的文章。
public static DataTable getGender()
{
DataTable DT = default(DataTable);
SqlConnection con = new SqlConnection(CnnString.ConnectionString.ToString());
SqlCommand cmd = new SqlCommand("ns_gender_get", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
try
{
//Fill the Dataset
da.Fill(ds, "Results");
DT = ds.Tables(0);
//**GOAL: I need to assign the DS.Table(0) to the DT (dataTable) so when this method is called it will return the table rows in the DT.
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
con = null;
}
return DT;
}
Actually, a DataSet
contains a collection of DataTables
. 实际上,一个DataSet
包含一个DataTables
的集合。 You can just take the first table: 您可以只使用第一张桌子:
DataTable dataTable = ds.Tables[0];
On the other hand, you can use a DataAdpter
to fill a DataTable
if you want, for sample: 另一方面,如果需要,您可以使用DataAdpter
来填充DataTable
,例如:
DataTable dt = new DataTable();
da.Fill(dt);
See more in: 更多内容:
https://msdn.microsoft.com/library/system.data.dataset.tables(v=vs.110).aspx https://msdn.microsoft.com/library/system.data.dataset.tables(v=vs.110).aspx
http://www.dotnetperls.com/sqldataadapter http://www.dotnetperls.com/sqldataadapter
-- Edits by original author of the question (for anyone else looking) The simple solution finally hit me -- -由问题的原始作者编辑(其他人都可以看)简单的解决方案终于打了我-
ds.Tables.Add(DT); // Code on how to add a table to a dataset!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.