asp.net.ph

DataTable.PrimaryKey Property

System.Data Namespace   DataTable Class


Sets or retrieves an array of columns that function as primary keys for the data table.

Syntax


Script DataTable.PrimaryKey [ = columnName ]

Property Value


columnName An array of DataColumn objects.

The property is read/write with no default value.

Exceptions


Exception Type Condition
DataException Occurs when 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 not 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

This example demonstrates how to set the primary key columns for a DataTable.

private void SetPrimaryKeys ( ) {
   // create a new DataTable and set two DataColumn objects as primary keys.
   DataTable myTable = new DataTable ( );
   DataColumn [ ] keys = new DataColumn [ 2 ];
   DataColumn myColumn;
   // create column 1.
   myColumn = new DataColumn ( );
   myColumn.DataType = System.Type.GetType ( "System.String" );
   myColumn.ColumnName = "FirstName";
   // add the column to the DataTable.Columns collection.
   myTable.Columns.Add ( myColumn );
   // add the column to the array.
   keys [ 0 ] = myColumn;

   // create column 2 and add it to the array.
   myColumn = new DataColumn ( );
   myColumn.DataType = System.Type.GetType ( "System.String" );
   myColumn.ColumnName = "LastName";
   myTable.Columns.Add ( myColumn );
   // add the column to the array.
   keys [ 1 ] = myColumn;
   // set the PrimaryKeys property to the array.
   myTable.PrimaryKey = keys;
}
  C# VB

This example shows how to return the primary key columns for a DataTable displayed in a DataGrid.

Private void GetPrimaryKeys ( DataTable myTable ) {
   // create the array for the columns.
   DataColumn [ ] colKeys = myTable.PrimaryKey;
   // get the number of elements in the array.
   Response.Write ( "Column Count: " + colKeys.Length );

   for ( int i = 0; i < colKeys.Length; i++ ) {
      Response.Write ( colKeys [ ].ColumnName + 
         colKeys [ ].DataType );
   }
}
  C# VB

See Also

DataTable Members   DataColumn   PrimaryKey   DataColumnCollection Skip Navigation Links




Home
Suggested Reading


Previous page Back to top Next page

© 2000-2010 Rey Nuñez All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note

You can help support asp.net.ph