Edit

Share via


DataColumn.AutoIncrement Property

Definition

Gets or sets a value that indicates whether the column automatically increments the value of the column for new rows added to the table.

public:
 property bool AutoIncrement { bool get(); void set(bool value); };
public bool AutoIncrement { get; set; }
[System.Data.DataSysDescription("DataColumnAutoIncrementDescr")]
public bool AutoIncrement { get; set; }
member this.AutoIncrement : bool with get, set
[<System.Data.DataSysDescription("DataColumnAutoIncrementDescr")>]
member this.AutoIncrement : bool with get, set
Public Property AutoIncrement As Boolean

Property Value

true if the value of the column increments automatically; otherwise, false. The default is false.

Attributes

Exceptions

The column is a computed column.

Examples

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");
    table.Columns.Add(column);
}
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
    table.Columns.Add(column)
End Sub

Remarks

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. 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.

You can create a new row using the ItemArray property of the DataRow class and passing in an array of values. This is a potential problem for a column with its AutoIncrement set to true, because its value is generated automatically. To use the ItemArray property, place null in the column's position in the array. For more information, see the ItemArray property of the DataRow class.

If the type of the column is SqlInt16 or SqlInt32, AutoIncrement will not work. Use Int16 or Int32 instead.

If the type of the column is SqlInt64 or SqlDecimal, AutoIncrement will only partially work. Use Int64 or Decimal instead.

When the AutoIncrementStep value is added to the current value, the overflow check is suppressed.

Applies to

See also