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

时间:2016-09-02 05:00:12

标签: c# asp.net vb.net

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");

如何在给定的datatable中添加主键。当我想要id列时 是独一无二的。

2 个答案:

答案 0 :(得分:1)

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

    angular.forEach(files, function(file) {
        file.upload = Upload.upload({
            url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
            data: {file: file}
        });`

然后你只通过这个名字和国家

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

您的ID会自动作为主键插入数据库。

在DataTable中,您可以像这样插入主键

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");

答案 1 :(得分:0)

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");