Primary Key

The primary key is a column or collection of columns that uniquely identify each row in the table. The PrimaryKey property accesses one or more DataColumn objects that define the primary key of the DataTable. The primary key acts both as a unique constraint for the table and allows records to be located using the Find( ) method of the DataTableRows collection, as discussed in the next section.

The primary key for a table is set by specifying an array of DataColumn objects from the table. The following example illustrates creating a primary key based on two columns:

// set the primary key based on two columns in the DataTable

DataTable dt = new DataTable("MyTable");

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

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

// ... add other table columns

// set the primary key

dt.PrimaryKey = new DataColumn[] {dt.Columns["PK_Field1"],


To remove the primary key, simply set the primary key object to null.

// remove the primary key

dt.PrimaryKey = null;

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.