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!

Steven Doggart
  • 43,358
  • 8
  • 68
  • 105
user902949
  • 529
  • 1
  • 5
  • 10

2 Answers2

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
        }
    }
}
Community
  • 1
  • 1
Steven Doggart
  • 43,358
  • 8
  • 68
  • 105
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;
        ...
    }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I'm confused.. this code will loop through the columns, THEN loop through the rows.. – Phillip Schmidt May 30 '12 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 '12 at 18:48
  • 3
    @PhillipSchmidt pretty typical if, say, you want to print the column headers etc – Marc Gravell May 30 '12 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 '12 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`: http://msdn.microsoft.com/en-us/library/system.data.dataset.tables.aspx – Marc Gravell May 30 '12 at 19:18
  • So "DataSet ds = new DataSet1();" should be used to make it an instance? – user902949 May 30 '12 at 19:50
  • @user902949 yes, but you'll need to fill it with data too - that will just be an empty dataset – Marc Gravell May 30 '12 at 21:27
  • Sorry to be ignorant here - I think I need to give more information. I built this dataset by Selecting Data|Add New Data Source and using ODBC connected it to a DB in an SQL instance. Now I want to go through all the tables and data in the tables in that DB. Am I out to lunch here? – user902949 May 30 '12 at 21:37
  • You'll need to update your question to show the code where you fill your data set so we can help you further. – Steven Doggart May 31 '12 at 00:21