A DataRow object represents a row of data in the table stored in a collection of columns. Rows belonging to the DataTable are stored as DataRow objects in a DataRowCollection object and are accessed through the Rows property of the DataTable. The Rows property accesses methods and properties that can add, remove, and examine the DataRow objects in a DataTable. This section examines some of the methods and properties of the DataRowCollection.

There are two methods that can add a row to a table. The Add( ) method takes either a DataRow argument or an object array of columns of the row to be added:

DataTable dt = new DataTable("MyTable");

dt.Columns.Add("Column1", typeof(System.Int32));

dt.Columns.Add("Column2", typeof(System.String));

DataRow newrow = dt.NewRow();

newrow["Column1"].Value = 1;

newrow["Column2"].Value = "DataRow 1";

// add a row using a reference to a DataRow


// add and create a DataRow in one statement

dt.Rows.Add(new Object[] {2, "DataRow 2"});

Additionally, a DataRow can be inserted at a specific point in the DataRowCollection using the InsertAt( ) method, which in addition to a reference to a DataRow, takes an argument specifying the zero-based index at which to insert the row.

// create a new row

DataRow row = dt.NewRow();

row.ItemArray = new Object[] {1, "DataRow 1"};

// insert a new row as the first item of the collection

dt.Rows.InsertAt(row, 0);

There are two methods that can examine and locate rows within the DataRow collection. The ...

Get ADO.NET in a Nutshell now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.