Solved

DataTable Traversal.

Posted on 2004-03-29
2
553 Views
Last Modified: 2012-08-14
I have a DataTable with one Column and four Rows.

 How do i iterate through this an load the string values into an array list.

ArrayList myList = new ArrayList();
foreach(DataRow dRow in dt.Rows)
{
  foreach(DataColumn dCol in dRow)
  {
    // What do  i do here. ?

   // or is there any better way to do it, because there is only one column and multiple rows.
  }
 
}


thanks,
steve.
0
Comment
Question by:steve_mick972
  • 2
2 Comments
 
LVL 22

Expert Comment

by:_TAD_
ID: 10708460
ArrayList myList = new ArrayList();
foreach(DataRow dRow in dt.Rows)  
     myList.Add(dRow[0]);
0
 
LVL 22

Accepted Solution

by:
_TAD_ earned 500 total points
ID: 10708543


The curly braces "{" are only required if you want to group more than one line together.  Since we are only executing one line in the foreach block, the curly braces are implicit.


Also... since we only have one column, we don't have to iterate through all of the columns... we will just "hard-code" a zero (the first, and only column).

Finally... the above code more or less copies the object from the table to the arraylist.  If the data you are ALWAYS going to return is of a particular type (like an int) then you may want to change from an arraylist to an int[] (better performance in the long run.



int[] myList = new int[dt.Rows.Count];
int i = 0;
foreach(DataRow dRow in dt.Rows)  
     myList[i++] = (int)dRow[0];

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.

713 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question