Primary Key for DataTable in C#

As we know, we can create a DataTable object in C# and can map to a database table, or we can manually add the rows in C# itself as shown below. Here we are adding three rows to DataTable dt and binding this table to DataGridView control.

using System;

using System.Data;

using System.Windows.Forms; 

namespace CSharpDataTableExp

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        } 

        private void Form1_Load(object sender, EventArgs e)

        {

            DataTable dt = new DataTable();

            dt.Columns.Add("Employee Id");

            dt.Columns.Add("Employee Name");

            dt.Columns.Add("Employee Salary"); 

            dt.Rows.Add(100, "A", 1000);

            dt.Rows.Add(101, "B", 2000);

            dt.Rows.Add(102, "C", 3000); 

            dataGridView1.DataSource = dt; 

        }

    }

} 

Sometimes we may have a requirement to add auto increment & Unique column to C# DataTable like Primary & Identity column in database table. We can achieve this by using AutoIncrement, AutoIncrementSeed, AutoIncrementStep, and Unique properties of Column & PrimaryKey property of DataTable in C# as below. 

using System;

using System.Data;

using System.Windows.Forms; 

namespace CSharpDataTableExp

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        } 

        private void Form1_Load(object sender, EventArgs e)

        {

            DataTable dt = new DataTable();

 

            DataColumn idColumn = dt.Columns.Add();

            idColumn.ColumnName = "Employee Id";

            idColumn.AutoIncrement = true;

            idColumn.AutoIncrementSeed = 100;

            idColumn.AutoIncrementStep = 1;

            idColumn.Unique = true;

 

            dt.PrimaryKey = new DataColumn[] { idColumn };          

            dt.Columns.Add("Employee Name");

            dt.Columns.Add("Employee Salary");

  

            DataRow dr1 = dt.NewRow();

            dr1["Employee Name"] = "A";

            dr1["Employee Salary"] = 1000; 

            DataRow dr2 = dt.NewRow();

            dr2["Employee Name"] = "B";

            dr2["Employee Salary"] = 2000; 

            DataRow dr3 = dt.NewRow();

            dr3["Employee Name"] = "C";

            dr3["Employee Salary"] = 3000; 

            dt.Rows.Add(dr1);

            dt.Rows.Add(dr2);

            dt.Rows.Add(dr3); 

            dataGridView1.DataSource = dt;             

        }

    }

} 

Here we are making “Employee Id” column as primary key and identity columns starting at 100 by using AutoIncrementSeed and AutoIncrementStep columns.