xorpower
xorpower

Reputation: 18973

Remove primary key in datatable

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;

Upvotes: 10

Views: 24335

Answers (2)

Miklos
Miklos

Reputation: 21

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;
}

Upvotes: 2

Pankaj Agarwal
Pankaj Agarwal

Reputation: 11311

You can remove primay key using

DataTable.PrimaryKey = null;

you can delete data table column using

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

Upvotes: 25

Related Questions