In this article I will explain with an example, how to add (insert) Primary Key column i.e. column with Unique values to DataTable in C# and VB.Net.
There is concept of Primary Key column in SQL Server Database, in similar way .Net allows us to add a Primary Key column i.e. column with Unique values to DataTable in C# and VB.Net.
 
 
Namespaces
You will need to import the following namespace.
C#
using System.Data;
 
VB.Net
Imports System.Data
 
 
Add (Insert) Primary Key column to DataTable in C# and VB.Net
In the following code snippet, first a DataTable is created and three columns are added to it. The first column i.e. the ID column is made a Primary Key column i.e. column with Unique values using the following properties.
PrimaryKey – This property is used to define the Primary Key columns in the DataTable. It accepts an array of columns. In the following example, the ID column is set as Primary Key column i.e. column with Unique values.
Finally rows are added to the DataTable.
C#
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");
 
VB.Net
Dim dt As New DataTable()
 
'Add columns to DataTable.
dt.Columns.AddRange(New DataColumn(2) {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")
 
Note: It is mandatory to insert unique values for a Primary Key column otherwise it will result in the following error.
 
Add (Insert) Primary Key column to DataTable in C# and VB.Net
 
 
Screenshot
Add (Insert) Primary Key column to DataTable in C# and VB.Net
 
 
Downloads