How loop through every column in every datarow in a datatable

  • Thread starter Thread starter VB Programmer
  • Start date Start date
V

VB Programmer

How do I loop through every column in every datarow in a datatable?

Here's the code I'm trying...

(dt = datatable)

For Each dr As DataRow In dt.Rows
For Each dc As DataColumn In dt.Columns
strTempRow += dc.ToString & ","
Next
Next

dc.ToString doesn't give me the VALUE of the column. Any ideas?
 
I'd try

Dim sb as New System.Text.StringBuilder
for i as Integer = 0 to dt.Rows.Count -1
for j as Integer = 0 to dt.Columns.Count -1
sb.Append(dt(i)(j).ToString())
Next
Next
 
This is what I have done to populate a combobox with items from a datagrid.
I don't know if this is exactly what you are looking for , but, it might
give you a couple of ideas.

james





Dim cm As Integer

Dim cols As Integer

cols = ds.Tables(0).Columns.Count - 1

cm = ds.Tables(0).Rows.Count - 1

Dim rowCount As Integer = cm

Dim colCount As Integer = cols

Dim row As Integer

dim col as Integer

For row = 0 To rowCount - 1

for col = 0 To colCount -1



Dim cellValue As Object = Me.DataGrid1(row, col)



ComboBox1.Items.Add((cellValue.ToString() + " "))

Next row

Next col

End If
 
VB Programmer,

Although the For index works as well, to give a direct answer with the For
each to make clear why your code is not working.
For Each dr As DataRow In dt.Rows

For Each dc As Object In dr.ItemArray
strTempRow += dc.ToString & ","
Next
Next
I hope this helps?

Cor
 
It doesn't give you the value of a column because a column object has no
member that represents a single row/column value. In fact, a column has no
method or properties that are specific to a single data item in the DataTable
it belongs to.

It looks like the The default member of the column object is the ColumnName
- at least that's what I get with an expression like "dc.tostring".

The DataRow object owns an ItemArray that contains a separate item object
for each column in the table. That's why you can get to individual
row/column elements by iterating through the collection of rows - and then
indexing through the item array, like this:

Dim dt As DataTable = ds.Tables(0)
Dim dr As DataRow
Dim dc As DataColumn
For Each dr In dt.Rows
For Each dc In dt.Columns
Console.Write(dr(dc.Ordinal) & vbTab)
Next
Console.WriteLine()
Next

It looks like your indexing through columns but you're actually indexing
through the ItemArray (which is the default object for the DataRow class.)

Here's annother way. This uses the column name to reference the item array
elements, as opposed to the numeric index value. But performance will suffer:

Dim dt As DataTable = ds.Tables(0)
Dim dr As DataRow
Dim dc As DataColumn
For Each dr In dt.Rows
For Each dc In dt.Columns
Console.Write(dr(dc.ToString) & vbTab)
Next
Console.WriteLine()
Next

So, it's not a question of how "For...Next" works, it's a question of the
specific makeup of the DataRow and DataColumn classes.

HTH
 
Back
Top