简体   繁体   中英

vb.net datatable loop through rows by specific column name

Hi i am trying to loop through row only in specific column. However i did not succeed, can any one help me. Here is my code, myXvalue = "CPI" is the column header Name.

Dim myXvalue = "CPI"

 For Each column As DataColumn In dt.Columns


                If column.ColumnName = myXvalue Then

                    For k As Integer = 0 To dt.Rows(myXvalue).Count - 1

                        Console.WriteLine(myXvalue & " === " & dt.Rows(0)(k).ToString)


                    Next

                    Console.ReadKey(True)


                End If

a. In visual basic.net a better practice is to define the types of fields or propeties.
use Dim myXvalue As String = "CPI" and not Dim myXvalue = "CPI" .
if you familiar with c# this convention is not exactly like var in c#:
Is VB's Dim the same as C#'s var?

b. the code below is one way to achieve what you need.

Private Sub Func()
    Dim myXvalue As String = "CPI"
    Dim colIndex As Integer = -1

    For i As Integer = 0 To dt.Columns.Count - 1
        If dt.Columns(i).ColumnName = myXvalue Then
            colIndex = i
            Exit For
        End If
    Next

    If colIndex = -1 Then
        ' only for safty if this column name is not exist
        Exit Sub
    End If

    For i As Integer = 0 To dt.Rows.Count - 1
        Console.WriteLine((myXvalue & "===" & dt.Rows(i).Item(colIndex).ToString()))
    Next

    Console.ReadKey(True)
End Sub

This should do the trick.

Dim dt As New DataTable()
For Each dr As DataRow In dt.Rows
    If dr.Item("myColumnHeaderName").ToString = "certainColumnValue" Then
        Console.WriteLine(dr.Item("myColumn").ToString())
    End If
Next

通过这个,您可以从一列获得所有项目的列表

Dim col_allitems as string = myData.Rows.Cast(Of DataRow).Select(Function(row) row.Item(1).ToString)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM