Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 699
xorpower Avatar asked Aug 09 '11 09:08

xorpower


People also ask

What is primary key in DataTable?

This identifying column or group of columns is called the primary key. When you identify a single DataColumn as the PrimaryKey for a DataTable, the table automatically sets the AllowDBNull property of the column to false and the Unique property to true.

How to remove constraints in DataTable in c#?

Ok this is more clear now: You can't remove constraints, they are disable during merge operation and then automatically enable after the merge if they can be enabled. As the error is like after the merge operation is completed, the Constraints can't be enabled due to some of the invalid values in target datatable.

How to set primary key in DataTable c#?

The primary key for a table is set by specifying an array of DataColumn objects from the table. The following example illustrates creating a primary key based on two columns: // set the primary key based on two columns in the DataTable DataTable dt = new DataTable("MyTable"); dt. Columns.


2 Answers

You can remove primay key using

DataTable.PrimaryKey = null;

you can delete data table column using

DataTable.Columns.Remove("column name here");
like image 136
Pankaj Agarwal Avatar answered Oct 02 '22 13:10

Pankaj Agarwal


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;
}
like image 21
Miklos Avatar answered Oct 02 '22 14:10

Miklos