Creating primary key on DataTable

Posted on 2005-05-13
Last Modified: 2007-12-19

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 ;
Question by:Kokas79
    LVL 22

    Accepted Solution


      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
    LVL 23

    Assisted Solution

    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)
    LVL 23

    Expert Comment

    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

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Live - One-on-One C# Help from Top Experts

    Solve your toughest problems, fast.
    C# experts are online now and ready to help you.

    Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
    This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
    Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
    Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now