March 2008
Intermediate to advanced
982 pages
22h 43m
English
You need to ensure that values for a column are unique for each row in a table.
Use the System.Data.UniqueConstraint class.
The solution creates a DataTable with two columns and adds a unique constraint to one of the columns. Rows are added including a row that violates the constraint. The results are output to the console.
The C# code in Program.cs in the project CreateUniqueConstraint is shown in Example 2-6.
Example 2-6. File: Program.cs for CreateUniqueConstraint solution
using System; using System.Data; namespace CreateUniqueConstraint { class Program { static void Main(string[] args) { // Create a table DataTable dt = new DataTable("Table-1"); // Add two columns dt.Columns.Add("Id", typeof(int)); dt.Columns.Add("Field1", typeof(string)).MaxLength = 50; // Create a unique constraint on Field1 UniqueConstraint uc1 = new UniqueConstraint("UniqueConstraint", dt.Columns["Field1"]); // Add the constraint to the table dt.Constraints.Add(uc1); // Output the properties of the table constraint added OutputConstraintProperties(dt); // Verify the unique constraint by adding rows try { AddRow(dt, 1, "Value 1"); AddRow(dt, 2, "Value 2"); AddRow(dt, 3, "Value 2"); } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); } Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } private static void OutputConstraintProperties(DataTable dt) { Console.WriteLine("DataTable {0} =< Constraint properties: ", dt.TableName); Console.WriteLine("\tName ...Read now
Unlock full access