DataTable Columns

A DataTable object represents a table of data in memory. It consists of rows and columns. Each column in a DataTable is represented by a DataColumn object. The DataColumn object defines the schema of the column, including its name, data type, and constraints.

Creating and Configuring DataColumns

You can create DataColumn objects and add them to a DataTable's Columns collection. When creating a DataColumn, you typically specify the column name and its data type.

Example: Adding Columns to a DataTable


using System;
using System.Data;

public class Example
{
    public static void Main(string[] args)
    {
        // Create a new DataTable
        DataTable dataTable = new DataTable("Customers");

        // Create DataColumn objects
        DataColumn idColumn = new DataColumn("CustomerID", typeof(int));
        DataColumn nameColumn = new DataColumn("CustomerName", typeof(string));
        DataColumn orderDateColumn = new DataColumn("OrderDate", typeof(DateTime));

        // Set CustomerID as the primary key
        idColumn.AutoIncrement = true;
        idColumn.AutoIncrementSeed = 1;
        idColumn.AutoIncrementStep = 1;
        idColumn.AllowDBNull = false; // Ensure CustomerID cannot be null

        // Add columns to the DataTable
        dataTable.Columns.Add(idColumn);
        dataTable.Columns.Add(nameColumn);
        dataTable.Columns.Add(orderDateColumn);

        // You can also add columns directly by specifying name and type
        dataTable.Columns.Add("City", typeof(string));

        Console.WriteLine($"DataTable '{dataTable.TableName}' created with columns:");
        foreach (DataColumn col in dataTable.Columns)
        {
            Console.WriteLine($"- {col.ColumnName} ({col.DataType.Name})");
        }
    }
}
                

Properties of DataColumn

Each DataColumn object has several important properties that define its behavior and characteristics:

Accessing Column Information

You can access the collection of columns in a DataTable using the Columns property. This property returns a DataColumnCollection object, which you can iterate through or access columns by their index or name.

Tip: When specifying a DataType, use the typeof() operator with the appropriate .NET type (e.g., typeof(int) for integers, typeof(string) for text, typeof(DateTime) for dates).

Constraints and Columns

DataColumn objects are intrinsically linked to constraints defined within the DataTable. The most common constraints applied to columns include:

These constraints are managed through the DataTable's Constraints collection, but they directly reference and operate on DataColumn objects.

Working with Expressions

The Expression property of a DataColumn is powerful. It allows you to define calculated columns or filter data. For example, you can create a calculated column that is the sum or average of other columns, or use an expression to filter rows based on specific criteria.

Example: Calculated Column


DataTable ordersTable = new DataTable("Orders");
ordersTable.Columns.Add("OrderID", typeof(int));
ordersTable.Columns.Add("ProductName", typeof(string));
ordersTable.Columns.Add("Quantity", typeof(int));
ordersTable.Columns.Add("Price", typeof(decimal));

// Add a calculated column for the extended price
DataColumn extendedPriceColumn = new DataColumn("ExtendedPrice", typeof(decimal), "Quantity * Price");
ordersTable.Columns.Add(extendedPriceColumn);

ordersTable.Rows.Add(1, "Laptop", 2, 1200.00m);
ordersTable.Rows.Add(2, "Keyboard", 5, 75.00m);
ordersTable.Rows.Add(3, "Mouse", 10, 25.00m);

Console.WriteLine("Orders with Extended Price:");
foreach (DataRow row in ordersTable.Rows)
{
    Console.WriteLine($"Order ID: {row["OrderID"]}, Product: {row["ProductName"]}, Extended Price: {row["ExtendedPrice"]:C}");
}
                

Summary

DataColumn objects are fundamental to defining the structure and data integrity of a DataTable. By understanding their properties and how to configure them, you can effectively model and manage data within your ADO.NET applications.