在c#和VB.Net中为DataTable添加(插入)主键列

本文关键字:插入 添加 DataTable VB Net 中为 | 更新日期: 2023-09-27 18:05:20

如何在c#和VB中添加(插入)主键列。

  DataTable dt = new DataTable();
 
//Add columns to DataTable.
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
 
//Add rows to DataTable.
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");

如何在给定数据表中添加主键。当我想要id column是独一无二的。

在c#和VB.Net中为DataTable添加(插入)主键列

必须在数据库中创建这样的表

create table tablename 
(
     id **primary key auto increment**, 
     name varchar(255), 
     country varchar(255)
)

然后像这样只传递姓名和国家

dt.Rows.Add( "John Hammond", "United States");
dt.Rows.Add( "Mudassar Khan", "India");
dt.Rows.Add( "Suzanne Mathews", "France");
dt.Rows.Add( "Robert Schidner", "Russia");

您的id将自动作为主键插入数据库。

在DataTable中像这样插入主键

DataTable table = new DataTable("childTable");
    DataColumn column;    
    column = new DataColumn();
    column.DataType= System.Type.GetType("System.Int32");
    column.ColumnName = "ChildID";
    column.AutoIncrement = true;
    column.Caption = "ID";
    column.ReadOnly = true;
    column.Unique = true;
table.Columns.Add(column);
DataTable dt = new DataTable();
//Add columns to DataTable.
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
//Set the Primary Key Column.
dt.PrimaryKey = new DataColumn[] { dt.Columns["Id"] };
//Add rows to DataTable.
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");