TheDeveloperBlog.com

Home | Contact Us

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

C# DataRow Examples

This C# tutorial shows the DataRow type from the System.Data namespace. It covers getting, adding and removing rows.

DataRow represents a row in a DataTable.

It is introduced by the System.Data namespace. It is added or removed from DataTables. It provides a useful container for structured referential data.

Add. When using a DataTable you are building in memory, you will almost certainly need to add DataRows. This example method shows how to first add DataColumns. It shows how to add five DataRows with the fields indicated in those columns.

DataColumn

Then: The DataTable is populated with five rows, each a separate dog with four data cells.

C# program that uses DataRow

static DataTable GetTable()
{
    // Here we create a DataTable with four columns.
    DataTable table = new DataTable();
    table.Columns.Add("Weight", typeof(int));
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Breed", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    // Here we add five DataRows.
    table.Rows.Add(57, "Koko", "Shar Pei", DateTime.Now);
    table.Rows.Add(130, "Fido", "Bullmastiff", DateTime.Now);
    table.Rows.Add(92, "Alex", "Anatolian Shepherd Dog", DateTime.Now);
    table.Rows.Add(25, "Charles", "Cavalier King Charles Spaniel", DateTime.Now);
    table.Rows.Add(7, "Candy", "Yorkshire Terrier", DateTime.Now);
    return table;
}

Add method signature. The Rows collection, which is a DataRowCollection instance, declares an Add method that receives an object array. This array must have an equal number of elements to the DataColumn fields.

Object array. To continue, we can create an explicit object array before adding it to the DataRowCollection on DataTable. This is useful for when you need to construct the values programmatically, or pass the arrays around in methods.

Note: The object array here has an array Length equal to the number of columns. Object arrays can store any element type.

Array Length PropertyObject Array

C# program that uses object array with DataTable

using System;
using System.Data;

class Program
{
    static void Main()
    {
	DataTable table = GetTable();
	//
	// We can instantiate a new object array and add it as a row.
	//
	object[] array = new object[4];
	array[0] = 7;
	array[1] = "Candy";
	array[2] = "Yorkshire Terrier";
	array[3] = DateTime.Now;
	table.Rows.Add(array);
    }
}

Get DataRow. Sometimes you will need to obtain a reference to a DataRow in your DataTable. This reference can be used for calling the Delete method or other methods, or for passing it as a parameter to methods.

Here: We use the Rows indexer, Rows[0], to get the first row. We get the last row in the Rows collection by subtracting 1 from the Count.

C# program that gets DataRows

using System;
using System.Data;

class Program
{
    static void Main()
    {
	//
	// Get the first row from the DataTable.
	//
	DataTable table = GetTable();
	DataRow row = table.Rows[0];
	Console.WriteLine(row["Breed"]);
	//
	// Get the last row in the DataTable.
	//
	DataRow last = table.Rows[table.Rows.Count - 1];
	Console.WriteLine(last["Breed"]);

    }
}

Output

Shar Pei
Yorkshire Terrier

Loop. Every DataRow will contain cells or fields. You will often need to examine these values while using DataTables in memory. Here we access the ItemArray on a DataRow, and then test each field in that row.

Note: You can avoid casting with the Field generic method. Please see the section further down for more info.

C# program that uses foreach on DataRow

using System;
using System.Data;

class Program
{
    static void Main()
    {
	//
	// Get the first row and loop over its ItemArray.
	//
	DataTable table = GetTable();
	DataRow row = table.Rows[0];
	foreach (object item in row.ItemArray)
	{
	    if (item is int)
	    {
		Console.WriteLine("Int: {0}", item);
	    }
	    else if (item is string)
	    {
		Console.WriteLine("String: {0}", item);
	    }
	    else if (item is DateTime)
	    {
		Console.WriteLine("DateTime: {0}", item);
	    }
	}
    }
}

Output

Int: 57
String: Koko
String: Shar Pei
DateTime: 4/6/2014 4:10:31 PM

In this loop, we do not know the exact type of each field in the ItemArray. We can loop over the ItemArray with the foreach loop and then test each field. This helps in methods that deal with flawed or invalid data.

Tip: You can find more detailed information on foreach-loops on DataRows on this site.

DataTable Foreach LoopIs

Remove. You will find that there are Remove and RemoveAt methods on the DataRow collection. These function differently, but in both cases you must be certain after Remove that you are accessing valid data.

Next: We remove the first row using Remove. If you try to access the DataRow, the runtime will throw an exception.

C# program that removes DataRow

using System;
using System.Data;

class Program
{
    static void Main()
    {
	//
	// Get the first row for the DataTable
	//
	DataTable table = GetTable();
	//
	// Get the row and remove it.
	//
	DataRow row = table.Rows[0];
	table.Rows.Remove(row);
	//
	// You can no longer access row[0].
	//
    }
}

Unhandled Exception:

System.Data.RowNotInTableException:
This row has been removed from a table and does not have any data.
BeginEdit() will allow creation of new data in this row.

Please remember that the exceptions are there to help you debug your program quicker. Don't let your blood pressure rise too much when they appear. They are actually making your life easier.

Delete. The Delete method will cleanly delete that DataRow. When you try to access that row's index, you will get the next row. In other words, the DataRow erases the row and you cannot access it all after you call Delete.

C# program that deletes DataRow

using System;
using System.Data;

class Program
{
    static void Main()
    {
	//
	// Get the first row for the DataTable
	//
	DataTable table = GetTable();
	DataRow row = table.Rows[0];
	//
	// Delete the first row. This means the second row is the first row.
	//
	row.Delete();
	//
	// Display the new first row.
	//
	row = table.Rows[0];
	Console.WriteLine(row["Name"]);
    }
}

Output

Fido

Field. There is a Field generic method on DataRow that returns strongly-typed fields without any casting. This provides clearer code and exploits the power of generic collections that were introduced in .NET.

So: You can, for example, access int, string, and DateTime fields using the Field method.

IntStringsDateTime

The type parameter, in sharp brackets, accepts the field type, while the function parameter accepts the field index. In complex programs, the Field extension can make life easier.

DataRow Field

Summary. We used DataRow in C# programs. This is a powerful collection in System.Data that will greatly help your program and keep its code understandable. The DataRow is used in almost every program that also uses the DataTable type.


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