7.4 Primary Key

The primary key is a column or collection of columns that uniquely identify each row in the table. The PrimaryKey property accesses one or more DataColumn objects that define the primary key of the DataTable . The primary key acts both as a unique constraint for the table and allows records to be located using the Find( ) method of the DataTableRows collection, as discussed in the next section.

The primary key for a table is set by specifying an array of DataColumn objects from the table. The following example illustrates creating a primary key based on two columns:

 // set the primary key based on two columns in the DataTable DataTable dt = new DataTable("MyTable"); dt.Columns.Add("PK_Field1", typeof(System.Int32)); dt.Columns.Add("PK_Field2", typeof(System.Int32)); // ... add other table columns // set the primary key dt.PrimaryKey = new DataColumn[] {dt.Columns["PK_Field1"],     dt.Columns["PK_Field2"]}; 

To remove the primary key, simply set the primary key object to null .

 // remove the primary key dt.PrimaryKey = null; 


ADO. NET in a Nutshell
ADO.NET in a Nutshell
ISBN: 0596003617
EAN: 2147483647
Year: 2005
Pages: 415

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net