14.12 Creating Unique Constraints

 <  Day Day Up  >  

You want to ensure that certain columns within a DataTable are unique.


Technique

Some columns within a DataTable must be unique to provide a way to uniquely identify a record. Furthermore, columns might need to be unique to prevent duplicate data entry. If your DataTable only needs to force a unique constraint on a small amount of columns, you can set the Unique property to true for that DataColumn , as shown in the following code:

 
 public Form1() {     InitializeComponent();     ds = new DataSet();     DataTable table = ds.Tables.Add("MyTable");     DataColumn keyCol = new DataColumn();     keyCol.ColumnName = "ID";     keyCol.DataType = typeof( int );     keyCol.AutoIncrement = true;     keyCol.Unique = true;     table.Columns.Add( keyCol ); } 

If you have several columns that need to be unique, you can use a UniqueConstraint collection. It allows you to create a group of unique columns by passing the collection to the Constraints property defined in the DataTable class. The UniqueConstraint class contains nine overloaded constructors, allowing for several options. In most cases, you can pass a collection of DataColumn objects or a string collection whose items represent the names of each column, which is shown in the following example:

 
 public Form1() {     InitializeComponent();     ds = new DataSet();     DataTable table = ds.Tables.Add("MyTable");     DataColumn keyCol = new DataColumn();     keyCol.ColumnName = "WinnerID";     keyCol.DataType = typeof( int );     keyCol.AutoIncrement = true;     table.Columns.Add( keyCol );     table.Columns.Add( "PrizeID", typeof(int) );     table.Columns.Add( "EMail", typeof(string) );     table.Constraints.Add(new UniqueConstraint(         "Constraints",         new string[]{"WinnerID", "PrizeID"},         false)); } 

Comments

The last example in this section used a group of columns to create unique constraints. Entering a value into the column that already exists in a different row causes an error. One of the nice things about the DataGrid is that it is designed to do the "right" thing when a user does something unexpected. Rather than deal with exceptions or event handlers to display a message that a unique constraint was violated, the DataGrid just displays the message itself without any extra work on your part.

In many cases, the data you display to a user is placed into a DataSet that is bound to a control. Before the data is displayed, you have the option of creating additional unique constraints by accessing the Columns property from a DataTable within the DataSet .

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

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