DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

How to add identity column to datatable using c#

By Ashok Nalam on 10 Dec 2013 | Category: C# | Tagged: .NET 
This snippet shows how to add identity column to datatable with an example.
  Discuss Add Comment   |  
Add rating Rate this resource  [Rated 5.00/5 by 1 people] 
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.
  Discuss Add Comment    
Add rating Rate this resource  [Rated 5.00/5 by 1 people] 
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9526  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (1)
 
1. By karthik mahalingam on 13 Dec 2013

nice, good info...

 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys