Solved

Adding a Primary Key column after a datatable has been created

Posted on 2013-05-13
3
465 Views
Last Modified: 2013-05-14
I'm importing values from a database into a local DataTable.

myDataTable = MyBLL.GetCustomComponents()

After the data has been imported into the datatable I want to add a primary key column called "ID" and then just have it auto-increment from 1 to the number of rows of data found in the datatable  

How can I do this?
0
Comment
Question by:cdemott33
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 1

Expert Comment

by:muh_abbas
ID: 39163810
Hello  cdemott33,

This article will help you.

http://www.java2s.com/Code/SQLServer/Constraints/CreatingaPrimaryKeyonanExistingTable.htm



Regards,
Abbas
0
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 500 total points
ID: 39164241
One option is to add column to the existing table but do not make it auto increment. Loop through the rows and populate manually.

Other option is demonstrated here

http://stackoverflow.com/questions/4310791/best-way-add-a-new-column-with-sequential-numbering-in-an-existing-data-table
0
 

Author Closing Comment

by:cdemott33
ID: 39164515
Thanks for you help.  I created a function that added the column than looped through the existing rows to added the primary key.

    Private Shared Function CreatePrimaryKeyColumn(ByVal dt As DataTable) As DataTable

        Dim dc As New DataColumn("PRIMARY_KEY")
        dc.DataType = GetType(Int32)

        dt.Columns.Add(dc)

        For i As Integer = 1 To dt.Rows.Count - 1
            dt.Rows(i)("PRIMARY_KEY") = i
        Next

        Return dt
    End Function
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

749 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