C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: You can access the DataRows in the first foreach-loop. But the ItemArray property requires that you cast the iteration variable.
ForeachDataRowGetTable: GetTable creates a DataTable and returns a reference to it. We use 2 foreach-loops to iterate over that data.
Var: Var describes an implicit reference to an object type. These objects are actually of type int, string and DateTime.
VarNext: This example just displays the object by invoking its ToString method implicitly through the Console.WriteLine method.
ConsoleC# program that loops over DataTable
using System;
using System.Data;
class Program
{
static void Main()
{
DataTable table = GetTable();
foreach (DataRow row in table.Rows)
{
Console.WriteLine("--- Row ---");
foreach (var item in row.ItemArray)
{
Console.Write("Item: "); // Print label.
Console.WriteLine(item);
}
}
Console.Read(); // Pause.
}
/// <summary>
/// Generates DataTable filled with patient information.
/// </summary>
static DataTable GetTable()
{
DataTable table = new DataTable(); // New data table.
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
table.Rows.Add(15, "Abilify", "Jacob", DateTime.Now);
table.Rows.Add(40, "Accupril", "Emma", DateTime.Now);
table.Rows.Add(40, "Accutane", "Michael", DateTime.Now);
table.Rows.Add(20, "Aciphex", "Ethan", DateTime.Now);
table.Rows.Add(45, "Actos", "Emily", DateTime.Now);
return table; // Return reference.
}
}
Output
--- Row ---
Item: 15
Item: Abilify
Item: Jacob
Item: 7/10/2009 8:31:40 AM
--- Row ---
Item: 40
Item: Accupril
Item: Emma
Item: 7/10/2009 8:31:40 AM
--- Row ---
Item: 40
Item: Accutane
Item: Michael
Item: 7/10/2009 8:31:40 AM
--- Row ---
Item: 20
Item: Aciphex
Item: Ethan
Item: 7/10/2009 8:31:40 AM
--- Row ---
Item: 45
Item: Actos
Item: Emily
Item: 7/10/2009 8:31:40 AM
Field: You can also use the generic Field method that receives one type parameter.
DataRow Field