sqllayman sqllayman - 7 months ago 17
Vb.net Question

Dynamically capture every data element (item) in a datarow and write to a textfile

I would like to dynamically loop through a result set and capture every row (datarow) and write to a text file without having to manually indicate each item in a row like item(0), item(1), item(2) ... etc.

Using sw As StreamWriter = New StreamWriter("C:\"file.txt")
For Each dr In ds.Tables("Table1").Rows
sw.WriteLine(dr.item(0).ToString() + "," + dr.item(1).ToString() +"," ...
Next

Answer

You need to get the table the row belongs to so that you can get the number of columns in the table then just loop through. The string concatanation needs some work but I'm sure you'll figure that out

Using sw As StreamWriter = New StreamWriter("C:\"file.txt")
For Each dr In ds.Tables("Table1").Rows
    Dim rowAsString as string
    For i as integer = 0 to dr.Table.Columns.Count - 1
        rowAsString += dr.item(i)
    Next
    sw.WriteLine(rowAsString)
Next