Nate Pet Nate Pet - 1 year ago 196 Question

VB.NET select columns from dataset

I have the following:

Dim dt As DataTable = ds.Tables(0)

Tables(0) has about 20 columns. I like to select only a couple. "PrID" is one of the fields.

I tried

Dim dt As DataTable = ds.Tables(0).Select("PrID")

without any success. Any idea?

Answer Source

One way is using the DataRow extension method Field which is strongly typed and supports nullable types:

For Each row As DataRow in ds.Tables(0).Rows
    Dim PrID As Int32 = row.Field(Of Int32)("PrID")

Edit: If you want another DataTable with a subset of columns of the original DataTable you can use the DataView of the table and it's ToTable method:

Dim displayView = New DataView(ds.Tables(0))
' if you're only interested in: PrID, Col2, Col3
Dim subset As DataTable = displayView.ToTable(false, "PrID", "Col2", "Col3")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download