42

I have a DataSet named DataSet1. It contains an unknown number of tables and an unknown number of columns and rows in those tables. I would like to loop through each table and look at all of the data in each row for each column. I'm not sure how to code this. Any help would be appreciated!

0

2 Answers 2

106
foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            // read item
        }
    }
}

Or, if you need the column info:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            object item = row[column];
            // read column and item
        }
    }
}
17

Just loop...

foreach(var table in DataSet1.Tables) {
    foreach(var col in table.Columns) {
       ...
    }
    foreach(var row in table.Rows) {
        object[] values = row.ItemArray;
        ...
    }
}
9
  • I'm confused.. this code will loop through the columns, THEN loop through the rows.. May 30, 2012 at 18:45
  • 1
    I think @Marc was just demonstrating that you can loop through the columns - you don't need to if you are just interested in the row values, but if you iterate the columns you can print out column headers which may be useful.
    – RobertMS
    May 30, 2012 at 18:48
  • 3
    @PhillipSchmidt pretty typical if, say, you want to print the column headers etc May 30, 2012 at 18:49
  • Hello - thanks for the reply - DatSet1.Tables is not valid. ".tables" is not a "member" of DatSet1. The only members are the tables themselves.
    – user902949
    May 30, 2012 at 19:08
  • 3
    @user902949 I'm assuming DataSet1 is an instance... not a type. If it is the type, then you need an instance, so just someInstance.Tables. But: .Tables very much is a member of an instance of DataSet: msdn.microsoft.com/en-us/library/… May 30, 2012 at 19:18

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.