VB.net add primary key identity column to datatable

Murray Brown
Murray Brown used Ask the Experts™
on
HI

I am using the following VB.net code to add an identity column. How do I set it as the primary key too?

            Dim dtNew As New DataTable()
            'Add columns to DataTable.
            '------------ ID Column -------------
            dtNew.Columns.Add("ID")
            'Set AutoIncrement True for the First Column.
            dtNew.Columns("ID").AutoIncrement = True
            'Set the Starting or Seed value.
            dtNew.Columns("ID").AutoIncrementSeed = 1

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2012
Top Expert 2014
Commented:
Create an array of columns that you want to use as the Primary Key, and set the Table.PrimaryKey value to that array:

Dim keys As DataColumn(1)
Keys(0) = YourTable.Columns("YourColumnName")
YourTable.PrimaryKey = Keys

If you need more than one:

Dim keys As DataColumn(2)
Keys(0) = YourTable.Columns("YourColumnName")
Keys(1) = YourTable.Columns("SecondColumn")
YourTable.PrimaryKey = Keys


Obviously the values in that column must be unique.
Murray BrownASP.net/VSTO Developer

Author

Commented:
Thank you very much

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial