Automatic Numbering for the Primary Key Column

You can designate a column in your table as an auto-increment column. This column will be automatically populated with a number that will be the primary key.

To set up an auto-increment column follow these steps

  1. Set the AutoIncrement property of your data column to true.
  2. Set the AutoIncrementSeed property to the value of the first number you want.
  3. Set the AutoIncrementStep property to the value you want to increment by each time a new row is added.

Following code sample shows how to create an Autoincrementing Primary Key

using System;

using System.Data;

namespace AutoIncrement

{

class Program

{

static void Main(string[] args)

{

// Create a table and add two columns Id and Name

DataTable objmyTable = new DataTable();

DataColumn objColumn = objmyTable.Columns.Add("Id", typeof(int));

objmyTable.Columns.Add("Name", typeof(string));

// Make the Id column the primary key

objmyTable.PrimaryKey = new DataColumn[] { objmyTable.Columns["Id"] };

// Set AutoIncrement property of column to true

objColumn.AutoIncrement = true;

// set autoincremented column starting at 25

objColumn.AutoIncrementSeed = 25;

// and incrementing by 25 with each new record added

objColumn.AutoIncrementStep = 25;

// Add rows to table

objmyTable.Rows.Add(new object[]{ null,"mukesh"});

objmyTable.Rows.Add(new object[]{null, "vinay"});

objmyTable.Rows.Add(new object[]{null, "ashish"});

Console.WriteLine("Id \tName");

Console.WriteLine("-------------");

foreach (DataRow row in objmyTable.Rows)

Console.WriteLine("{0}\t{1}", row["Id"], row["Name"]);

Console.WriteLine("\nPress any key to continue.");

Console.ReadLine();

}

}

}

Output :


AutoIncrement.png