MSDN Documentation

DataColumn Object

The DataColumn object represents a column in a DataTable. It defines the schema of the data within that column, including its name, data type, and whether it can contain null values.

Overview

A DataColumn is a fundamental part of the ADO.NET data model. Each column in a DataTable is an instance of the DataColumn class. You can think of it as defining the metadata for a specific piece of data across all the rows in a table.

Key Properties

Creating and Adding a DataColumn

You can create a DataColumn by instantiating the DataColumn class directly or by using the Columns.Add() method of a DataTable.

Tip: When adding a column directly, you must associate it with a DataTable before it can be added to the table's collection. The DataTable.Columns.Add() overload is generally more convenient.

Example: Creating a DataColumn with specific properties

using System;
using System.Data;

// Create a DataTable
DataTable myTable = new DataTable("Customers");

// Create DataColumns
DataColumn idColumn = new DataColumn();
idColumn.ColumnName = "CustomerID";
idColumn.DataType = typeof(int);
idColumn.AutoIncrement = true;
idColumn.AutoIncrementSeed = 1;
idColumn.AutoIncrementStep = 1;
idColumn.AllowDBNull = false; // Primary key columns usually cannot be null

DataColumn nameColumn = new DataColumn("CustomerName", typeof(string));
nameColumn.AllowDBNull = false;
nameColumn.MaxLength = 100;

DataColumn registeredDateColumn = new DataColumn("RegisteredDate", typeof(DateTime));
registeredDateColumn.DefaultValue = DateTime.Now;

// Add columns to the DataTable
myTable.Columns.Add(idColumn);
myTable.Columns.Add(nameColumn);
myTable.Columns.Add(registeredDateColumn);

// You can also use the simpler overload:
// myTable.Columns.Add("CustomerID", typeof(int));
// myTable.Columns.Add("CustomerName", typeof(string));
// myTable.Columns.Add("RegisteredDate", typeof(DateTime));

Using Expressions

The Expression property allows you to define calculated columns or to filter/sort data.

Example: Creating a calculated column

// Assuming 'myTable' has columns 'Quantity' (int) and 'UnitPrice' (decimal)
            DataColumn totalCostColumn = new DataColumn("TotalCost", typeof(decimal));
            totalCostColumn.Expression = "Quantity * UnitPrice";
            myTable.Columns.Add(totalCostColumn);
            

Example: Filtering rows using an expression

// Filter for customers registered after a specific date
            DataView myView = new DataView(myTable);
            myView.RowFilter = "RegisteredDate > '#1/1/2023#'";
            

Common Use Cases

Note: When defining a primary key for a DataTable, the corresponding DataColumn objects should typically have AllowDBNull set to false and Unique set to true.