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
DataColumnto aDataTableand configures the columnCreates and configures a
DataColumnand adds it to aDataTableAdds a
DataColumnto aDataTableand configures it using theAdd()method of theColumnCollectionof theDataTableexposed through theColumnspropertyCreates multiple
DataColumnobjects, configures them, and adds them to theDataTableusing theAddRange()method of theColumnCollectionof theDataTable
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 ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access