• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 653
  • Last Modified:

Creating primary key on DataTable


In the following code why does the author create a unique constraint and a primary key on the same column? If you wanna make a column the primary key one, then obviously every value will be unique right? and also....why is there a need for the array? i thought only the last line would be sufficient

DataColumn[]  pk = new DataColumn[1] ;
pk[0] = dt.Columns["ProductID"] ;

dt.Constraints.Add ( new UniqueConstraint ( "PK_Products" , pk[0] ) ) ;

dt.PrimaryKey = pk ;
  • 2
2 Solutions
Mohammed NasmanSoftware DeveloperCommented:

  You could write the previous code as one sentence like

dt.Constraints.Add(new UniqueConstraint("PK_Products", dt.Columns[0] ,true) ) ;

You need to use array of DataColumn, when you would to create combined primay key, from two fields or more
dt.Constraints.Add ( new UniqueConstraint ( "PK_Products" , pk[0] ) ) ; is superfluous as when you set it as a PrimaryKey, it is marked as Unique, Not Nullable (AllowDBNull is false)
The only time where it makes sense is if the primary key is a composite key itself. Then You'd have to set the settings manually in each column
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now