Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add identity column to datatable using c#

Tags:

c#

How to add identity column to datatable using c#. Im using Sql compact server.

like image 497
Shiny Avatar asked May 15 '10 06:05

Shiny


2 Answers

If the DataTable is already populated. you can use below method

void AddAndPopulateDataTableRowID(DataTable dt, string col, bool isGUID)
    {
        if(isGUID)
            dt.Columns.Add(col, typeof(System.Guid));
        else
            dt.Columns.Add(col, typeof(System.Int32));

        int rowid = 1;
        foreach (DataRow dr in dt.Rows)
        {
            if (isGUID)
                dr[col] = Guid.NewGuid();
            else
                dr[col] = rowid++;
        }

    }
like image 64
x-coder Avatar answered Sep 27 '22 17:09

x-coder


You could try something like this maybe?

private void AddAutoIncrementColumn()
{
    DataColumn column = new DataColumn();
    column.DataType = System.Type.GetType("System.Int32");
    column.AutoIncrement = true;
    column.AutoIncrementSeed = 1000;
    column.AutoIncrementStep = 10;

    // Add the column to a new DataTable.
    DataTable table = new DataTable("table");
    table.Columns.Add(column);
}
like image 35
Josh OD Brown Avatar answered Sep 27 '22 16:09

Josh OD Brown