Articles → ADO.NET → Unique Constraint In Ado.Net

Unique Constraint In Ado.Net






Syntax


UniqueConstraint <class_object> = new UniqueConstraint("<name_of_constraint>",<collection_of_data_columns>);





Example




DataTable dt = new DataTable();
dt.Columns.Add("CustomerID", Type.GetType("System.Int32"));
dt.Columns.Add("CompanyName", Type.GetType("System.String"));
dt.Columns.Add("Location", Type.GetType("System.String"));










UniqueConstraint uc = new UniqueConstraint("CustConstraint", new DataColumn[] {
  dt.Columns["CustomerID"]
});
dt.Constraints.Add(uc);




DataRow dr = dt.NewRow();
dr["CustomerID"] = 1;
dr["CompanyName"] = "ABC2";
dr["Location"] = "Delhi";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["CustomerID"] = 1;
dr["CompanyName"] = "ABC";
dr["Location"] = "Delhi6";
dt.Rows.Add(dr);










UniqueConstraint uc = new UniqueConstraint("CustConstraint", new DataColumn[] {
  dt.Columns["CustomerID"], dt.Columns["CompanyName"]
});
dt.Constraints.Add(uc);




DataRow dr = dt.NewRow();
dr["CustomerID"] = 1;
dr["CompanyName"] = "ABC";
dr["Location"] = "Delhi";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["CustomerID"] = 1;
dr["CompanyName"] = "ABC1";
dr["Location"] = "Delhi";
dt.Rows.Add(dr);






DataRow dr = dt.NewRow();
dr["CustomerID"] = 1;
dr["CompanyName"] = "ABC";
dr["Location"] = "Delhi";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["CustomerID"] = 1;
dr["CompanyName"] = "ABC";
dr["Location"] = "Delhi6";
dt.Rows.Add(dr);








UniqueConstraint uc = new UniqueConstraint("CustConstraint", new DataColumn[] {
  dt.Columns["CustomerID"], dt.Columns["CompanyName"], dt.Columns["Location"]
});
dt.Constraints.Add(uc);




DataRow dr = dt.NewRow();
dr["CustomerID"] = 1;
dr["CompanyName"] = "ABC";
dr["Location"] = "Delhi";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["CustomerID"] = 1;
dr["CompanyName"] = "ABC";
dr["Location"] = "Delhi6";
dt.Rows.Add(dr);




DataRow dr = dt.NewRow();
dr["CustomerID"] = 1;
dr["CompanyName"] = "ABC";
dr["Location"] = "Delhi";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["CustomerID"] = 1;
dr["CompanyName"] = "ABC";
dr["Location"] = "Delhi";
dt.Rows.Add(dr);









Posted By  -  Karan Gupta
 
Posted On  -  Friday, December 9, 2011

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250