This documentation is archived and is not being maintained.

Defining Primary Keys (ADO.NET)

A database table commonly has a column or group of columns that uniquely identifies each row in the table. This identifying column or group of columns is called the primary key.

When you identify a single DataColumn as the PrimaryKey for a DataTable, the table automatically sets the AllowDBNull property of the column to false and the Unique property to true. For multiple-column primary keys, only the AllowDBNull property is automatically set to false.

The PrimaryKey property of a DataTable receives as its value an array of one or more DataColumn objects, as shown in the following examples. The first example defines a single column as the primary key.

workTable.PrimaryKey = New DataColumn() {workTable.Columns("CustID")}

' Or

Dim columns(1) As DataColumn
columns(0) = workTable.Columns("CustID")
workTable.PrimaryKey = columns

The following example defines two columns as a primary key.

workTable.PrimaryKey = New DataColumn() {workTable.Columns("CustLName"), _

' Or

Dim keyColumn(2) As DataColumn
keyColumn(0) = workTable.Columns("CustLName")
keyColumn(1) = workTable.Columns("CustFName")
workTable.PrimaryKey = keyColumn