How to iterate all items in a given row in the DataTable . I have the following code to iterate all rows, I want another For loop to iterate all cells in a given row ?
For Each row As DataRow In dt.Rows Next row
I can access each row, but I want to access each column on the row, as I don’t know the name and the count of the columns ,..
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You have to loop through DataRow.ItemArray. In C#, we can do it by following code:
foreach (DataRow dr in dt.Rows)
{
foreach (var item in dr.ItemArray)
{
Console.WriteLine(item);
}
}
This is equivalent to the following VB.NET code.
For Each dr As DataRow In dt.Rows
For Each item In dr.ItemArray
Console.WriteLine(item)
Next
Next
Method 2
For Each row As DataRow In dt.Rows
For Each column As DataColumn in dt.Columns
Console.WriteLine(row(column))
Next column
Next row
Method 3
your code is correct.
you cn use this code…
Dim tbl As New DataTable()
Dim datarow As DataRow
tbl.Columns.Add("column1")
datarow = tbl.NewRow()
datarow("column1") = "Data1"
tbl.Rows.Add(datarow)
For Each dr As DataRow In tbl.Rows
For Each value In dr.ItemArray
Label1.Text = value.ToString()
Next
Next
Method 4
You can use DataRow.ItemArray to do the job also
the code would look something like this
For Each item As var In Row.ItemArray
//do something
Next
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0