NGWS SDK Documentation  

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DataTable.PrimaryKey

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

[Visual Basic]
Public Property PrimaryKey As DataColumn ()
[C#]
public DataColumn[] PrimaryKey {get; set;}
[C++]
public: __property DataColumn* get_PrimaryKey();
public: __property void set_PrimaryKey(DataColumn*[]);
[JScript]
public function get PrimaryKey() : DataColumn[];
public function set PrimaryKey(DataColumn[]);

Property Value

An array of DataColumn objects.

Exceptions

Exception Type Condition
DataException The key is a foreign key.

Remarks

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.

Example [Visual Basic]

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

[Visual Basic]

Private Sub GetPrimaryKeys()
   Dim colArr() As DataColumn
   Dim t As DataTable
   Dim i As Integer

   t = DataGrid1.DataGridTable.DataTable
   colArr = t.PrimaryKey
   ' Use the Ubound method to determine the number in the array.
   Console.WriteLine("Column Count", UBound(colArr))
   For i = 0 To UBound(colArr) - 1
      Console.WriteLine(colArr(i).ColumnName, colArr(i).DataType.ToString)
   Next
End Sub

Private Sub SetPrimaryKeys()
   ' Create a new DataTable and set two DataColumn objects as primary keys..
   Dim t As DataTable = New DataTable
   Dim keys(1) As DataColumn 
   Dim dc As DataColumn
   ' Create column 1.
   dc = New DataColumn
   dc.DataType = System.Type.GetType("System.String")
   dc.ColumnName= "FirstName"
   ' Add the column to the DataTable.Columns collection.
   t.Columns.Add(dc)
   ' Add the column to the array.
   keys(0) = dc

   ' Create column 2 and add it to the array.
   dc = New DataColumn
   dc.DataType = System.Type.GetType("System.String")
   dc.ColumnName="LastName"
   keys(1) = dc
   t.Columns.Add dc
   ' Set the PrimaryKeys property to the array.
   t.PrimaryKey = keys

End Sub

See Also

DataTable Class | DataTable Members | System.Data Namespace | DataColumn | PrimaryKey | ColumnsCollection