How to add identity column to datatable using c#
How to add identity column to datatable using c#. Im using Sql compact server.开发者_运维问答
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);
}
DataTable table = new DataTable("table");
DataColumn dc= table.Columns.Add("id", typeof(int));
dc.AutoIncrement=true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
// Add the new column name in DataTable
table.Columns.Add("name",typeof(string));
table.Rows.Add(null, "A");
table.Rows.Add(null, "B");
table.Rows.Add(null, "C");
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++;
}
}
You don't do autoincrement on DataTable (or front-end for that matter), unless you want to make your application a single user application only.
If you need the autoincrement, just do it in database, then retrieve the autoincremented id produced from database to your front-end.
See my answer here, just change the SqliteDataAdapter to SqlDataAdapter, SqliteConnection to SqlConnection, etc : anyway see why I get this "Concurrency Violation" in these few lines of code??? Concurrency violation: the UpdateCommand affected 0 of the expected 1 records
Just my two cents. Auto-increment is useful in a Winform
app (stand alone as Michael Buen rightly said), i.e.:
DatagridView
is being used to display data that does not have a "key field", the same can be used for enumeration.
I dont think its a good idea to use autoincrement on datatable if you are using insert and delete to a datatable because the number will not be rearranget, no final i will share a small idea how can we use autoincrement manual.
DataTable dt = new DataTable();
dt.Columns.Add("ID",typeof(int));
dt.Columns.Add("Produto Nome", typeof(string));
dt.Rows.Add(null, "A");
dt.Rows.Add(null, "B");
dt.Rows.Add(null, "C");
for(int i=0;i < dt.Rows.Count;i++)
{
dt.Rows[i]["ID"] = i + 1;
}
always when finalizing the insert or delete must run this loop
for(int i=0;i < dt.Rows.Count;i++)
{
dt.Rows[i]["ID"] = i + 1;
}
精彩评论