How Can I Select What Columns Come In From A Dataset Into A Datatable?
Solution 1:
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 outtheseposts for more info.
Solution 2:
// Assumes that connection is a valid SqlConnection object.stringqueryString="SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapteradapter=newSqlDataAdapter(queryString, connection);
DataSetcustomers=newDataSet();
adapter.Fill(customers, "Customers");
DataTabletable= customers.Tables[0];
Instead of "CustomerID, CompanyName" you can put the columns you want to select.
For further learning check this MSDN link.
Post a Comment for "How Can I Select What Columns Come In From A Dataset Into A Datatable?"