In this article I will explain with an example, how to add (insert) Identity column to DataTable in C# and VB.Net.
There is concept of Identity column in SQL Server Database, in similar way .Net allows us to add an Identity column 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) Identity AutoIncrement (Auto Number) 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 an Identity i.e. AutoIncrement (Auto Number) column using the following properties.
AutoIncrement – This property is set to true.
AutoIncrementSeed – This property is set to the value the automatic numbering should start. For example, in this case it is set to 1 hence the automatic numbering will start from 1.
AutoIncrementStep – This property is set to the difference value between the automatic numbers example, in this case it is set to 1 and hence the automatic numbering will be 1, 2, 3,…N. But if it is set to 2 the automatic numbering will be 1, 3, 5,….N.
Finally rows are added to the DataTable and since the first column is Identity i.e. AutoIncrement (Auto Number) column, its value is passed as NULL.
Note: It is mandatory to pass the value of the Identity i.e. AutoIncrement (Auto Number) column as NULL.
 
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 AutoIncrement True for the First Column.
dt.Columns["Id"].AutoIncrement = true;
 
//Set the Starting or Seed value.
dt.Columns["Id"].AutoIncrementSeed = 1;
 
//Set the Increment value.
dt.Columns["Id"].AutoIncrementStep = 1;
 
//Add rows to DataTable.
dt.Rows.Add(null, "John Hammond", "United States");
dt.Rows.Add(null, "Mudassar Khan", "India");
dt.Rows.Add(null, "Suzanne Mathews", "France");
dt.Rows.Add(null, "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 AutoIncrement True for the First Column.
dt.Columns("Id").AutoIncrement = True
 
'Set the Starting or Seed value.
dt.Columns("Id").AutoIncrementSeed = 1
 
'Set the Increment value.
dt.Columns("Id").AutoIncrementStep = 1
 
'Add rows to DataTable.
dt.Rows.Add(Nothing, "John Hammond", "United States")
dt.Rows.Add(Nothing, "Mudassar Khan", "India")
dt.Rows.Add(Nothing, "Suzanne Mathews", "France")
dt.Rows.Add(Nothing, "Robert Schidner", "Russia")
 
 
Screenshot
Add (Insert) AutoIncrement (Auto Number) column to DataTable in C# and VB.Net
 
 
Downloads