2010-05-15 83 views

回答

20

你可以尝试这样的事情吗?

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); 
} 
+0

当添加到一个现有的DataTable中的数据,它会自动填充现有的行中的新列? – Lunyx 2017-05-12 13:35:50

1

除非您只想让应用程序成为单一用户应用程序,否则您不会在DataTable(或前端)上自动增量。

如果您需要自动增量,只需在数据库中执行该操作,然后将从数据库生成的自动增量标识检索到您的前端。

见我的答案在这里,只是改变SqliteDataAdapter到SqlDataAdapter的,SqliteConnection到的SqlConnection等: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

+1

我正在阅读平面文件中的数据,并需要向DataTable添加行号 - 有时候这是有效的,并且不会让我的应用程序成为单个用户。 – MrTelly 2012-07-16 10:33:32

+0

是啊,或者输出.....我生成的输出是由多个独立的读取组成的,需要以单个序列结束。这是DataTable的一个非常重要的本地使用......与“单用户”类似的隔离,但不完全相同。 – 2017-12-31 23:44:45

0

只是我的两分钱。自动增量处于Winform应用程序非常有用(单独作为迈克尔·布埃诺说得很有道理),即:

DatagridView被用于显示不具有“关键领域”的数据,同样可以用于枚举。

0

我不认为它使用自动增量上的数据表,如果您使用的插入和删除的数据表,因为数量不会被rearranget一个好主意,没有最终我将分享一个小想法,我们如何使用自动增量手册。

  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; 
     } 

总是敲定时插入或删除,必须运行此循环

  for(int i=0;i < dt.Rows.Count;i++) 
     { 
      dt.Rows[i]["ID"] = i + 1; 
     } 
+0

这真是令人困惑。并且改变'DataTable'不会改变数据库,我相信这是OPs问题的重要部分。 – andr 2013-01-18 00:51:24

6
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"); 
1

如果已经填充了DataTable的。你可以使用下面的方法

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++; 
     } 

    } 
相关问题