2.1. Creating a DataColumn and Adding It to a DataTable

Problem

You need to create a column and add it to a DataTable.

Solution

Use the Add() or AddRange() method of the DataColumnCollection of the DataTable exposed through its Columns property.

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

The C# code in Program.cs in the project CreateDataColumnAddDataTable is shown in Example 2-1.

Example 2-1. File: Program.cs for CreateDataColumnAddDataTable solution

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 ...

Get ADO.NET 3.5 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.