lockworld
6/8/2017 - 7:25 PM

Iterating through dataset in C#

Iterating through dataset in C#

using System;
using System.Data;

class Program
{
    static void Main()
    {
        DataTable table1 = new DataTable("patients");
        table1.Columns.Add("name");
        table1.Columns.Add("id");
        table1.Rows.Add("sam", 1);

        DataTable table2 = new DataTable("medications");
        table2.Columns.Add("id");
        table2.Columns.Add("medication");
        table2.Rows.Add(1, "atenolol");
        table2.Rows.Add(6, "trifluoperazine");

        // Create a DataSet.
        DataSet set = new DataSet("office");
        set.Tables.Add(table1);
        set.Tables.Add(table2);

        // Loop over DataTables in DataSet.
        DataTableCollection collection = set.Tables;
        for (int i = 0; i < collection.Count; i++)
        {
            DataTable table = collection[i];
            Console.WriteLine("{0}: {1}", i, table.TableName);
        }

        // Write name of first table.
        Console.WriteLine("x: {0}", set.Tables[0].TableName);

        // Write row count of medications table.
        Console.WriteLine("y: {0}", set.Tables["medications"].Rows.Count);
        
        // Get names of all columns
        foreach(DataColumn column in set.Tables[0].Columns) 
        { 
          Console.WriteLine(column.ColumnName); 
        }
    }
}