JimDel
JimDel

Reputation: 4359

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

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.

Upvotes: 0

Views: 2828

Answers (2)

Bibhu
Bibhu

Reputation: 4081

    // 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.

Upvotes: 1

mattmc3
mattmc3

Reputation: 18315

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.

Upvotes: 5

Related Questions