VB.NET从数据集中选择列

时间:2012-08-23 21:37:40

标签: vb.net

我有以下内容:

    Dim dt As DataTable = ds.Tables(0)

表(0)有大约20列。我喜欢只选择一对。 “PrID”是其中一个领域。

我试过

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

没有任何成功。任何的想法?

3 个答案:

答案 0 :(得分:3)

一种方法是使用强类型的DataRow扩展方法Field并支持可空类型:

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

修改:如果您希望其他DataTable包含原始DataTable的列子集,则可以使用该表的DataView及其ToTable方法:

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")

答案 1 :(得分:0)

您可以使用。

获取PRID列
    Dim dt As New DataTable
    Dim columns As String() = "PrID".Split(",")
    dt = ds.Tables(0).DefaultView.ToTable(String.Empty, False, columns)

答案 2 :(得分:0)

    'first create a new Dataview 
    Dim [Dataview] As New DataView

    'here add the table to Dataview you want to filter its columns
    [Dataview].Table = Ds.Tables(" here Write TableName ")

    'here you can display selected Columns in Datatable 
    Dim [datatable] As DataTable = [Dataview].ToTable(False, "desired column Name ", "desired Column Name")
    'here you can display selected Columns  in DatagridView1
    DataGridView1.DataSource = [Dataview].ToTable(False, "desired column Name ", "desired Column Name")