asp.net - Add (Insert) Primary Key column to DataTable in C# and VB.Net -


datatable dt = new datatable();  //add columns datatable. dt.columns.addrange(new datacolumn[3] { new datacolumn("id"), new datacolumn("name"), new datacolumn("country") });   //add rows 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"); 

how add primary key in given datatable.when want id column unique.

you have create table in database

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

then pass name , country this

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

your id automatically inserted in database primary key.

in datatable insert primary key this

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

Comments