1

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
tharun
  • 63
  • 1
  • 2
  • 11

3 Answers3

1

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
Jonathan Applebaum
  • 5,738
  • 4
  • 33
  • 52
  • Thanks Jonathana this what i was looking for :) – tharun May 31 '17 at 22:45
  • Hi Jonathana while extracting these data (dt.Rows(i).Item(colIndex).ToString()) to text file its taking only 2 decimals and skipping rest, Do i need to format the cells to take entire value ? – tharun Jun 06 '17 at 20:53
  • that wasent part of the question but try to cast it to double: `CType(dt.Rows(i).Item(colIndex).ToString(), Double).ToString()` – Jonathan Applebaum Jun 06 '17 at 21:05
0

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
Nick Painter
  • 720
  • 10
  • 13
-1

With this you get a list of all Items from one Column

Dim col_allitems as string = myData.Rows.Cast(Of DataRow).Select(Function(row) row.Item(1).ToString)
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92