How can I select what columns come in from a DataSet into a DataTable?

▼魔方 西西 提交于 2019-12-02 18:04:41

问题


Being new to working with Data, I hope I'm asking this properly. How can I select what columns come in from a DataSet into a DataTable? I know I can fill a DataTable by using...

DataTable table = dataSet1.Tables[0];

but this brings in all the columns. How can I fill a DataTable with only certain columns?

I'm using .NET 3.5, C#, and a SQL CE 3.5 single table database.

Thanks.


回答1:


    // Assumes that connection is a valid SqlConnection object.

string queryString = "SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);

DataSet customers = new DataSet();
adapter.Fill(customers, "Customers");

DataTable table = customers.Tables[0];

Instead of "CustomerID, CompanyName" you can put the columns you want to select.

For further learning check this MSDN link.




回答2:


The DataTable is actually filled via a DataAdapter when the DataSet is created. Once you run your query, the columns in the DataTable are set. But, you can use a DataView to apply an additional filter and a column reduction to a DataTable, but the cost of querying the database and pulling data has already occurred, so you should consider making sure your query doesn't pull back more than you need. MSDN is a great resource.

Of course if you're just now learning this, it bears mentioning that while ADO.NET is important to know foundationally, you should be aware that there's a lot of momentum away from raw ADO.NET lately towards things like Entity Framework. While SQL will never die, nor should it, you're going to have to write a whole lot more plumbing code when using ADO.NET then you would with a nice ORM. Check out these posts for more info.



来源:https://stackoverflow.com/questions/6419263/how-can-i-select-what-columns-come-in-from-a-dataset-into-a-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!