TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# DataTable Foreach Loop

This C# example code uses foreach on the Rows property from DataTable.

DataTable Foreach loop. DataTable can be used with foreach.

It is possible to loop through all the elements in the DataTable. The DataTable allows the use of the foreach-loop and its enumerator. But iterating over the items in a DataRow can be confusing.

Example. The DataTable class provides two public instance properties that are ideal for this task. These are Rows, which returns a typed collection of rows, and ItemArray, which returns a collection of cell values boxed in objects.

Object

Note: You can access the DataRows in the first foreach-loop. But the ItemArray property requires that you cast the iteration variable.

DataRow

Looping over DataTable instance: C#

using System;
using System.Data;

class Program
{
    static void Main()
    {
	DataTable table = GetTable(); // Get the data table.
	foreach (DataRow row in table.Rows) // Loop over the rows.
	{
	    Console.WriteLine("--- Row ---"); // Print separator.
	    foreach (var item in row.ItemArray) // Loop over the items.
	    {
		Console.Write("Item: "); // Print label.
		Console.WriteLine(item); // Invokes ToString abstract method.
	    }
	}
	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)); // Add five columns.
	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); // Add five data rows.
	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

This program first generates an example DataTable instance. The GetTable method locally allocates the data and then returns a reference to that data on the managed heap. We use two foreach-loops to iterate over that data.

Console.Write call on objects. In the innermost foreach-loop body in the Main method, the "var item" declaration describes an implicit reference to an object type. These objects are actually of type int, string and DateTime.

Var

Note: This example just displays the object by invoking its ToString method implicitly through the Console.WriteLine method.

Console.WriteLine

When iterating over the ItemArray elements, it is often easier to cast the cell values to their original types. You can do this with the is-cast or as-cast. You can also use the generic Field method that receives one type parameter.

IsAs

Summary. We examined the foreach-loop construct on the DataTable object. The code example allows you to display and save all cell values in the DataTable at any time. We used the instance Rows and ItemArray properties for this purpose.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf