Select Query on a DataTable to obtain a new DataTable

Hi,

I'd like to execute a select query on a DataTable, and obtain as a result a new DataTable only populating with the columns that I've defined in my query.

For example, I've got a DataTable with 3 columns: DataSetId (Long Integer), X (double), Y (double).
And I want to execute the query "SELECT X,Y FROM MyTable WHERE DataSetId=2", to obtain a new datatable with only two columns X and Y, and the selected rows.

Any ideas?

Thanks!
LVL 2
JulienVanAsked:
Who is Participating?
 
philipjonathanConnect With a Mentor Commented:
You can just use DataView:
DataView dv = new DataView(dataTable, "DataSetId = 2", string.Empty, DataViewRowState.CurrentRows);
0
 
Jaime OlivaresConnect With a Mentor Software ArchitectCommented:
use the dataview as suggested by philip, and hide the datasetid column if you are using a datagridview.
0
 
Jaime OlivaresSoftware ArchitectCommented:
if you want to change the dataview's filter at any time you can do something like:

dv.RowFilter = "DataSetId = " + someId.ToString();
0
 
JulienVanAuthor Commented:
Thank you for your quick responses, using a dataview is a great idea.

I use myDataView.ToTable(false, new string[] { "X", "Y" }); to obtain my new datatable.
0
All Courses

From novice to tech pro — start learning today.