Export (0) Print
Expand All

DataTable.PrimaryKey Property

Gets or sets an array of columns that function as primary keys for the data table.

Namespace:  System.Data
Assembly:  System.Data (in System.Data.dll)

'Declaration
Public Property PrimaryKey As DataColumn()

Property Value

Type: System.Data.DataColumn()
An array of DataColumn objects.

ExceptionCondition
DataException

The key is a foreign key.

The primary key of a table must be unique to identify the record in the table. It's also possible to have a table with a primary key made up of two or more columns. This occurs when a single column can't contain enough unique values. For example, a two column primary key might consist of a "FirstName" and "LastName" column. Because primary keys can be made up of more than one column, the PrimaryKey property consists of an array of DataColumn objects.

The first example shows how to return the primary key columns for a DataTable displayed in a DataGrid. The second example demonstrates how to set the primary key columns for a DataTable.

Private Sub GetPrimaryKeys(table As DataTable)
   ' Create the array for the columns. 
   Dim columns() As DataColumn 
   columns = table.PrimaryKey

   ' Get the number of elements in the array.
   Console.WriteLine("Column Count: " & columns.Length.ToString())
   Dim i As Integer 
   For i = 0 To columns.GetUpperBound(0)
      Console.WriteLine(columns(i).ColumnName & columns(i).DataType.ToString())
   Next i
End Sub 

Private Sub SetPrimaryKeys()
   ' Create a new DataTable and set two DataColumn objects as primary keys. 
   Dim table As DataTable = new DataTable()
   Dim keys(2) As DataColumn
   Dim column  As DataColumn

   ' Create column 1.
   column = New DataColumn()
   column.DataType = System.Type.GetType("System.String")
   column.ColumnName= "FirstName" 

   ' Add the column to the DataTable.Columns collection.
   table.Columns.Add(column)
   ' Add the column to the array.
   keys(0) = column

   ' Create column 2 and add it to the array.
   column = New DataColumn()
   column.DataType = System.Type.GetType("System.String")
   column.ColumnName = "LastName"
   table.Columns.Add(column)

   ' Add the column to the array.
   keys(1) = column

   ' Set the PrimaryKeys property to the array.
   table.PrimaryKey = keys
End Sub

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft