Create Unique Constraint

Create Unique Constraint


UniqueConstraint Class represents a restriction on a set of columns in which all values must be unique.

Following example show how to create Unique Constraint

 

using System;

using System.Data;

 

namespace CreateUniqueConstraint

{

classProgram

    {

staticvoid Main(string[] args)

        {

// Create a table

DataTable objmyTable = newDataTable("MyTable");

// Add two columns

            objmyTable.Columns.Add("Id", typeof(int));

            objmyTable.Columns.Add("Name", typeof(string));

// Create a unique constraint on Field1

UniqueConstraint objUnique = newUniqueConstraint("UniqueConstraint", objmyTable.Columns["Id"]);

// Add the constraint to the table

            objmyTable.Constraints.Add(objUnique);

 

 

// Verify the unique constraint by adding rows

try

            {

                objmyTable.Rows.Add( 1, "mukesh");

                objmyTable.Rows.Add(2, "vinay");

                objmyTable.Rows.Add(1, "ashish");

            }

catch (Exception ex)

            {

Console.WriteLine("\nError: {0}", ex.Message);

            }

 

Console.WriteLine("\nPress any key to continue.");

Console.ReadLine();

        }

 

    }

}

 

Output :


uniqueconstraint.png

Next Recommended Reading Creating a Foreign Key Constraint