Creating a DataColumn and Adding It to a DataTable

The solution creates, configures, and adds a column to a DataTable using four different techniques:

  • Adds a DataColumn to a DataTable and configures the column
  • Creates and configures a DataColumn and adds it to a DataTable
  • Adds a DataColumn to a DataTable and configures it using the Add() method of the ColumnCollection of the DataTable exposed through the Columns property
  • Creates multiple DataColumn objects, configures them, and adds them to the DataTable using the AddRange() method of the ColumnCollection of the DataTable

Code:

 using System;
using System.Data;

namespace CreateDataColumnAddDataTable
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();

            // Add the column to the DataTable to create
            DataColumn col1 = dt.Columns.Add();
            // Configure the column — integer with a default = 0 that
            // does not allow nulls
            col1.ColumnName= “Column-1”;
            col1.DataType = typeof(int);
            col1.DefaultValue = 0;
            col1.Unique = true;
            col1.AllowDBNull = false;

            // Create and configure the column
            DataColumn col2 = new DataColumn();
            // Configure the column — string with max length = 50
            col2.ColumnName = “Column-2”;
            col2.DataType = typeof(string);
            col2.MaxLength = 50;
            // Add the column to the DataTable
            dt.Columns.Add(col2);

            // Add a column directly using an overload of the Add()
            // method of the DataTable.Columns collection — the column
            // is a string with max length = 50
            dt.Columns.Add(“Column-3”, typeof(string)).MaxLength = 50;

            // Add multiple existing columns to the DataTable
            DataColumn col4 = new DataColumn(“Column-4”);
            // … configure column 4
            DataColumn col5 = new DataColumn(“Column-5”, typeof(int));
            // Add columns 4 and 5 to the DataTable
            dt.Columns.AddRange(new DataColumn[] { col4, col5 });

            // Output the columns in the DataTable to the console
            Console.WriteLine(“DataTable has {0} DataColumns named:”,
                dt.Columns.Count);
            foreach (DataColumn col in dt.Columns)
                Console.WriteLine(“\t{0}”, col.ColumnName);
            Console.WriteLine(“\nPress any key to continue.”);
            Console.ReadKey();
        }
    }
}

The DataColumn constructor has five overloads:

	DataColumn()
	DataColumn(string columnName)
	DataColumn(string columnName, Type dataType)
	DataColumn(string columnName, Type dataType, string expression)
	DataColumn(string columnName, Type dataType, string expression,
	    MappingType mappingType)


ColumnName
 Name of the column to be created.
DataType
 Column data type, from supported members of the Type class.
Expression
 Expression used to create the column.
MappingType
 Specifies how columns are mapped to elements or attributes when transformed to an XML document.

 The MappingType enumeration lets you specify Element, Attribute, SimpleContent, or Hidden.

 

 

DataColumn

DataColumn is a true object, inheriting from the System.Object namespace
A DataColumn is exactly what it sounds like: a column of data.

The DataColumn is the foundation of a DataTable and has very similar properties to a column in a relational database table.

The data in a DataTable is represented in the same manner. So, a DataTable is made up of DataColumns and DataRows.

DataTable contains a collection of DataColumns, and this could be considered the DataTable’s schema, or structure

DataColumn Properties

AllowDBNull

True or False, default is True. Determines whether the column will allow Null values. Null values represent the absence of a value and generally require special handling

AutoIncrement

True or False, default is False. This indicates whether the DataColumn will automatically increment a counter. When this value is True, a numeric value will be placed in this column. If the column is not of a Int16, Int32, or Int64, it will be coerced to Int32. If the DataTable is to be populated by an array, a Null must be placed in the array position corresponding to the

AutoIncrement

column in the DataTable.If an expression is already present when this property is set, an exception of type ArgumentException is thrown.

AutoIncrementSeed

Default is 1. This is the starting value of the first row in the column if the AutoIncrement property is set to True. AutoIncrementStep Default is 1. This is the value that the counter is incremented by for each new row in the DataColumn is the AutoIncrement property is True. Caption Caption for the column. If a caption is not specified, the ColumnName is returned. ColumnMapping Determines the MappingType of the column, which is used during the WriteXML method of the parent DataSet.These are the MappingTypes and their descriptions:

  • Attribute XML attribute
  • Element XML element
  • Hidden Internal structure
  • SimpleContent XmlText node

ColumnName

Name of the column in the DataColumnCollection. If a ColumnName is not specified before the column is added to the DataColumnCollection, the DataColumnName is set to the default (Column1, Column2, and so on).

Container

Returns the container of the component (inherited from MarshalByValueComponent). DataType Sets, or returns, the type of data in the column. These types are members of the System.Type class. Throws an exception of type ArgumentException if data is present in the DataColumn when the DataType is set.

DefaultValue

Determines the default value for a new row.

DesignMode

Returns a value indicating whether the component is in design mode (inherited from MarshalByValueComponent).

Expression

Defines an expression used to filter rows or create an aggregate column.

ExtendedProperties

Returns a collection of custom user information.

MaxLength

Defines the maximum length of a text column.

Namespace

Defines or returns the namespace of the DataColumn.

Ordinal

Returns the index or position of the column in the DataColumnCollection collection.

Prefix Defines or returns an XML prefix used to alias the namespace of the DataTable.

ReadOnly

True or False, default is False. Indicates whether the column allows changes once a row has been added to the table.

Site

Returns a reference to the parent. If Null reference or nothing, the DataColumn does not reside in a container (inherited from MarshalByValueComponent).

Table

Returns a reference to the DataTable of which the column belongs.

Unique

True or False, default is false. Determines if the values in each row of the column must be unique.

DataColumn Methods

Dispose

Releases resources used by the component (inherited from MarshalByValueComponent). Overloaded.

Equals

Returns True if two instances of the Object are equal (inherited from Object). Overloaded.

GetHashCode

Hash function useful for hashing algorithms and data structures similar to hash tables (inherited from Object).

GetService

Returns the implementer of iServiceProvider interface (inherited from MarshalByValueComponent).

GetType

Returns the type of the current instance (inherited from Object). ToString Returns the existing column Expression. Overridden.