System.Data Namespace DataColumn Class
Sets or retrieves the default value for the column when creating new rows.
Script |
DataColumn.DefaultValue [ = strValue ] |
strValue |
A value appropriate to the column's DataType. |
The property is read/write with no default value.
Exception Type |
Condition |
InvalidCastException |
When adding a row, the default value is not an instance of the column's data type. |
A default value is the value that is automatically assigned to the column when a DataRow is created. By setting a default value, you can give the user an idea of what information to input. On the other hand, you can use the DefaultValue property to automatically insert a value that shouldn't be touched by the user; for example, the current date and time of the row's creation.
When AutoIncrement is set to true, there can be no default value.
You can create a new row using the DataRow class's ItemArray property and passing the method an array of values. This is a potential problem for a column with a default value because its value is generated automatically. To use the ItemArray property with such a column, place a null reference in the column's position in the array. For more details, see the ItemArray property.
The following example initializes several DataColumn objects with different data types, and sets appropriate default values to each column.
Private Sub CreateColumns ( )
Dim myCol As DataColumn
Dim myTable As New DataTable
myCol = New DataColumn
With myCol
.DataType = System.Type.GetType ( "System.String" )
.DefaultValue = "Address"
.Unique = False
End With
myTable.Columns.Add ( myCol )
myCol = New DataColumn
With myCol
.DataType = System.Type.GetType ( "System.Int32" )
.DefaultValue = 100
End With
myTable.Columns.Add ( myCol )
myCol = New DataColumn
With myCol
.DataType = System.Type.GetType ( "System.DateTime" )
.DefaultValue = "1/1/2001"
End With
myTable.Columns.Add ( myCol )
Dim myRow As DataRow
' add one row. Since it has default values, no need to set values yet.
myRow = myTable.NewRow
myTable.Rows.Add ( myRow )
End Sub
Private Sub CreateColumns ( )
Dim myCol As DataColumn
Dim myTable As New DataTable
myCol = New DataColumn
With myCol
.DataType = System.Type.GetType ( "System.String" )
.DefaultValue = "Address"
.Unique = False
End With
myTable.Columns.Add ( myCol )
myCol = New DataColumn
With myCol
.DataType = System.Type.GetType ( "System.Int32" )
.DefaultValue = 100
End With
myTable.Columns.Add ( myCol )
myCol = New DataColumn
With myCol
.DataType = System.Type.GetType ( "System.DateTime" )
.DefaultValue = "1/1/2001"
End With
myTable.Columns.Add ( myCol )
Dim myRow As DataRow
' add one row. Since it has default values, no need to set values yet.
myRow = myTable.NewRow
myTable.Rows.Add ( myRow )
End Sub |
|
C# |
VB |
DataColumn Members DataType ItemArray AutoIncrement UniqueConstraint