Remove primary key in datatable

半城伤御伤魂 提交于 2020-04-07 02:36:57

问题


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;

回答1:


You can remove primay key using

DataTable.PrimaryKey = null;

you can delete data table column using

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



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


来源:https://stackoverflow.com/questions/6994111/remove-primary-key-in-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!