In this article I will explain with an example, how to add (insert) Column with Default Value to DataTable in C# and VB.Net.
When Column is specified a Default Value then if its value is not passed i.e. if the value is NULL or Nothing then in such scenario the Default Value is set for that column.
 
 
Namespaces
You will need to import the following namespace.
C#
using System.Data;
 
VB.Net
Imports System.Data
 
 
Add (Insert) Column with Default Value to DataTable in C# and VB.Net
In the following code snippet, first a DataTable is created and three columns are added to it. The first column i.e. the ID column is assigned a Default Value 0.
Finally rows are added to the DataTable and for some rows the value of ID column is passed while for some it is passed as NULL and in such scenario the Default Value i.e. 0 is inserted.
Note: It is mandatory to pass the value of the Default Value column as NULL in cases when the Default Value needs to be inserted.
 
C#
DataTable dt = new DataTable();
 
//Add columns to DataTable.
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
 
//Set the Default Value.
dt.Columns["Id"].DefaultValue = 0;
 
//Add rows to DataTable.
dt.Rows.Add(null, "John Hammond", "United States");
dt.Rows.Add(1, "Mudassar Khan", "India");
dt.Rows.Add(null, "Suzanne Mathews", "France");
dt.Rows.Add(3, "Robert Schidner", "Russia");
 
VB.Net
Dim dt As New DataTable()
 
'Add columns to DataTable.
dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id"), New DataColumn("Name"), New DataColumn("Country")})
 
'Set the Default Value.
dt.Columns("Id").DefaultValue = 0
 
'Add rows to DataTable.
dt.Rows.Add(Nothing, "John Hammond", "United States")
dt.Rows.Add(1, "Mudassar Khan", "India")
dt.Rows.Add(Nothing, "Suzanne Mathews", "France")
dt.Rows.Add(3, "Robert Schidner", "Russia")
 
 
Screenshot
Add (Insert) Column with Default Value to DataTable in C# and VB.Net
 
 
Downloads