DataColumn.AutoIncrement 屬性


取得或設定值,指出對於加入至資料表的新資料列而言,該資料行是否自動遞增資料行的值。Gets or sets a value that indicates whether the column automatically increments the value of the column for new rows added to the table.

 property bool AutoIncrement { bool get(); void set(bool value); };
public bool AutoIncrement { get; set; }
member this.AutoIncrement : bool with get, set
Public Property AutoIncrement As Boolean


如果資料行值自動遞增,則為 true,否則為 falsetrue if the value of the column increments automatically; otherwise, false. 預設為 falseThe default is false.



該資料行是計算的資料行。The column is a computed column.


下列範例會設定AutoIncrementAutoIncrementSeedAutoIncrementStep屬性。The following example sets the AutoIncrement, AutoIncrementSeed, and AutoIncrementStep properties.

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");
Private Sub AddAutoIncrementColumn()
    Dim column As New DataColumn()
    column.DataType = System.Type.GetType("System.Int32")
    With column
        .AutoIncrement = True
        .AutoIncrementSeed = 1000
        .AutoIncrementStep = 10
    End With

    ' Add the column to a new DataTable.
    Dim table As DataTable
    table = New DataTable
End Sub


如果設定此屬性時,此資料行的類型不是 Int16、int32 或 Int64,則DataType會將屬性強制轉型為 Int32。If the type of this column is not Int16, Int32, or Int64 when this property is set, the DataType property is coerced to Int32. 如果這是計算資料行,就會產生例外狀況。An exception is generated if this is a computed column. Expression設定屬性。The Expression property is set. 只有當此資料行的資料列值(加入至資料行集合時)等於預設值時,才會使用遞增的值。The incremented value is used only if the row's value for this column, when added to the columns collection, is equal to the default value.

您可以使用ItemArray DataRow類別的屬性來建立新的資料列,並傳入值的陣列。You can create a new row using the ItemArray property of the DataRow class and passing in an array of values. 這是AutoIncrement將資料行設定為true的潛在問題,因為它的值會自動產生。This is a potential problem for a column with its AutoIncrement set to true, because its value is generated automatically. 若要使用ItemArray屬性,請null將資料行位置放在陣列中。To use the ItemArray property, place null in the column's position in the array. 如需詳細資訊,請ItemArray參閱DataRow類別的屬性。For more information, see the ItemArray property of the DataRow class.

如果資料行的類型是SqlInt16SqlInt32AutoIncrement將無法使用。If the type of the column is SqlInt16 or SqlInt32, AutoIncrement will not work. 請改用 Int16 或 Int32。Use Int16 or Int32 instead.

如果資料行的類型是SqlInt64SqlDecimalAutoIncrement則只會部分工作。If the type of the column is SqlInt64 or SqlDecimal, AutoIncrement will only partially work. 請改用 Int64 或 Decimal。Use Int64 or Decimal instead.

AutoIncrementStep值加入至目前的值時,會隱藏溢位檢查。When the AutoIncrementStep value is added to the current value, the overflow check is suppressed.