Remove primary key in datatable

21,800

Solution 1

You can remove primay key using

DataTable.PrimaryKey = null;

you can delete data table column using

DataTable.Columns.Remove("column name here");

Solution 2

I found that sometimes after removing PrimaryKey from a DataTable:

MyDataTable.PrimaryKey = null;

the Unique setting remains true on the member columns of the deleted PrimaryKey.

My solution:

 public static void KillPrimaryKey(DataTable LocDataTable)
{
  int LocPriKeyCount = LocDataTable.PrimaryKey.Length;
  string[] PrevPriColumns = new string[LocPriKeyCount];

  // 1. Store ColumnNames in a string Array
  for (int ii = 0; ii < LocPriKeyCount; ii++) PrevPriColumns[ii] = LocDataTable.PrimaryKey[ii].ColumnName;
  // 2. Clear PrimaryKey
  LocDataTable.PrimaryKey = null;
  // 3. Clear Unique settings
  for (int ii = 0; ii < LocPriKeyCount; ii++) LocDataTable.Columns[PrevPriColumns[ii]].Unique = false;
}
Share:
21,800
xorpower
Author by

xorpower

Reached 500 Repo on May 22'11 Reached 600 Repo on Jul 29'11 Reached 700 Repo on Aug 10'11 Reached 800 Repo on Sep 09'11 Reached 900 Repo on Oct 13'11 Reached (&amp; crossed) 1000 Repo during Mar 14-19'12 Reached 1300 Repo on May 8 2013

Updated on July 05, 2020

Comments

  • xorpower
    xorpower almost 4 years

    is there a way to remove primary key from the datatable Or is there any way to remove the constraints of "PK" first and then remove the column itself?

    Thanks!

    UPDATED:

     dtTable.Columns.Add(new System.Data.DataColumn("PRIMARY_KEY", typeof(System.Int32)));
     dtTable.PrimaryKey = new DataColumn[1] { dtTable.Columns["PRIMARY_KEY"] }; // throws an error
     dtTable.Columns["PRIMARY_KEY"].AutoIncrement = true;