Compartir a través de


Defining a Primary Key for a Table

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 myColArray(1) As DataColumn
myColArray(0) = workTable.Columns("CustID")
workTable.PrimaryKey = myColArray
[C#]
workTable.PrimaryKey = new DataColumn[] {workTable.Columns["CustID"]};

// Or

DataColumn[] myColArray = new DataColumn[1];
myColArray[0] = workTable.Columns["CustID"];
workTable.PrimaryKey = myColArray;

The following example defines two columns as a primary key.

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

' Or

Dim myKey(2) As DataColumn
myKey(0) = workTable.Columns("CustLName")
myKey(1) = workTable.Columns("CustFName")
workTable.PrimaryKey = myKey
[C#]
workTable.PrimaryKey = new DataColumn[] {workTable.Columns["CustLName"], 
                                         workTable.Columns["CustFName"]};

// Or

DataColumn[] myKey = new DataColumn[2];
myKey[0] = workTable.Columns["CustLName"];
myKey[1] = workTable.Columns["CustFName"];
workTable.PrimaryKey = myKey;

See Also

Creating and Using DataTables | DataTable Class