In order to make DataTable column as identity column we need to set 3 properties
DataColumn.AutoIncrement - True
DataColumn.AutoIncrementSeed - Starting Value
DataColumn.AutoIncrementStep - Increment value
Below code shows how add identity/normal column to DataTable , adds data to table and retrieves the data.
Example:
using System;
using System.Data;
namespace DotNetMirror
{
class IdentityColumnToDataTable
{
static void Main()
{
DataTable dt = CreateDataTable();
//read datatable
foreach (DataRow dr in dt.Rows)
{
Console.WriteLine("ID:{0} - Name:{1}", dr["ID"].ToString(), dr["Name"].ToString());
}
Console.ReadLine();
}
static DataTable CreateDataTable()
{
//identity column
DataColumn idcolumn = new DataColumn("ID", typeof(int));
idcolumn.AutoIncrement = true;
idcolumn.AutoIncrementSeed = 5;
idcolumn.AutoIncrementStep = 1;
//normal column
DataColumn namecolumn = new DataColumn("Name", typeof(string));
// Add columns to a DataTable.
DataTable table = new DataTable("Student");
table.Columns.Add(idcolumn);
table.Columns.Add(namecolumn);
//add data to table
table.Rows.Add(null,"A");
table.Rows.Add(null,"B");
return table;
}
}
}
Output:
ID:5 - Name:A
ID:6 - Name:B
Note: If observe the code we passed null value to identity column while adding table data but the output is generated with identity data.