Home

The Columns of a Table

 

Fundamentals of Columns of a Table

 

Introduction

A column is a technique of categorizing some values that belong to a table. Based on this, one category from a list of a video application can be made of video titles. Another category can contain the years the videos were released. Yet another category can contain a number used to identify the format of the video. Here is an example of a table:

 

Video Title Director © Year Length Format Rating
A Few Good Men Rob Reiner 1992 138 Minutes 1 R
The Distinguished Gentleman Jonathan Lynn   112 Minutes 2 R
The Lady Killers Joel Coen & Ethan Coen   104 Minutes 2 R
Fatal Attraction Adrian Lyne 1987 120 Minutes 1 R
Her Alibi Bruce Beresford 1989 94 Minutes 2 PG-13
The Manchurian Candidate Jonathan Demme 2004 129 Minutes 2 R

A category of information of a table is called a column. The string on top of each column allows the user to identify what that column is used for. That string is called the column header.

To support the columns of a table, the .NET Framework provides the DataColumn class.

Practical Learning Practical Learning: Introducing Columns

  1. Start Microsoft Visual C# and create a Console Application named VideoCollection2
  2. To create a new class, in the Class View, right-click VideoCollection2 -> Add -> Class...
  3. Set the Name to Video and press Enter
  4. Change the file as follows:
     
    using System;
    using System.Data;
    
    namespace VideoCollection2
    {
        public class Video
        {
            private DataSet dsVideoCollection;
    
            private DataTable tblActors;
            private DataTable tblVideos;
    
            public Video()
            {
                dsVideoCollection = new DataSet("VideoCollection");
    
                tblActors = new DataTable("Actors");
                dsVideoCollection.Tables.Add(tblActors);
    
                tblVideos = new DataTable("Videos");
                dsVideoCollection.Tables.Add(tblVideos);
            }
    
            public void ShowTables()
            {
                int i = 1;
    
                Console.WriteLine("Video Collection - Tables");
                foreach (DataTable tbl in dsVideoCollection.Tables)
                    Console.WriteLine("{0}. {1}", i++, tbl.TableName);
            }
        }
    }
  5. Access the Program.cs file and change it as follows:
     
    using System;
    
    namespace VideoCollection2
    {
        public class Program
        {
            static int Main(string[] args)
            {
                Video vdo = new Video();
                vdo.ShowTables();
    
                return 0;
            }
        }
    }
  6. To save the file, on the Standard toolbar, click the Save All button
  7. Accepts all defaults and click Save
  8. Execute the application to make sure it is working fine:
     
    Video Collection - Tables
    1. Actors
    2. Videos
    Press any key to continue . . .
  9. Close the DOS window

Creating a Column

To create a column, you can first declare a variable of type DataColumn. The DataColumn class is equipped with five constructors. The default constructor allows you to create a column without giving details. Here is an example:

using System;
using System.Data;

public class VideoCollection
{
    public VideoCollection()
    {
        DataColumn colCategoryID = new DataColumn();
    }
}

If you are planning to reference the column from more than one method, you should declare it at a class level. Here is an example:

using System;
using System.Data;

public class VideoCollection
{
    private DataColumn colCategoryID;

    public VideoCollection()
    {
        colCategoryID = new DataColumn();
    }
}

To distinguish them, each column must have a specific and unique name. The name of a column allows you and the compiler to identify a particular column. The name must follow the rules of variables in C#. To specify the object name of a column, when creating it, you can use the second constructor whose syntax is:

public DataColumn(string name);

This constructor expects as argument the name of the column. Here is an example:

using System;
using System.Data;

public class VideoCollection
{
    private DataColumn colCategoryID;

    public VideoCollection()
    {
        colCategoryID = new DataColumn("CategoryID");
    }
}

The name of a column is supported with the ColumnName property of the DataColumn class. This property is of type string.

If you have already declared a DataColumn object, to specify or change its name, assign the desired string to the DataColumn.ColumnName property. Here is an example:

using System;
using System.Data;

public class VideoCollection
{
    private DataColumn colCategoryID;
    private DataColumn colCategory;

    public VideoCollection()
    {
        colCategoryID = new DataColumn("CategoryID");
        colCategory = new DataColumn();
        colCategory.ColumnName = "Category";
    }
}

Based on these descriptions, the minimum information needed to create a column is a name. If you don't specify a name, a default name is assigned to the new column.

Operations on the Columns of a Table

 

Introduction

The columns of a table are stored in a property called Columns of the DataTable class. The Columns property is an object of type DataColumnCollection. The DataColumnCollection class provides everything that is necessary to create and manage any column. The DataColumnCollection class is in fact a collection of objects.

Adding a Column to a Table

To make a column part of a table, you must add it to the table's collection of columns. The DataColumnCollection class is equipped with a method called Add() that allows you to add a column to the table.

The DataColumnCollection.Add() method is overloaded with 3 versions. One of the versions uses the following syntax:

public virtual DataColumn Add();

When called, this create creates a new column and return it. The compiler would assign a default name to the column. If this is the first column, it would be named Column1. If it is the second column, it would be named Column2, and so on. You can still specify or change the name of a column created with the above version of the Add() method. To do this, assign the desired string to the DataColumn.ColumnName. Here is an example:

using System;
using System.Data;

public class VideoCollection
{
    private DataColumn colCategoryID;
    private DataColumn colCategory;
    private DataColumn colDirectorID;

    private DataTable dtDirectors;

    public VideoCollection()
    {
        colCategoryID = new DataColumn("CategoryID");
        colCategory = new DataColumn();
        colCategory.ColumnName = "Category";

	dtDirectors = new DataTable();
        colDirectorID = dtDirectors.Columns.Add();
    }
}

If you want to specify the name of the new column when calling the DataColumnCollection.Add() method, use the following version:

public virtual DataColumn Add(string name);

This method takes as argument the name of the new column and returns that new column. Here is an example:

using System;
using System.Data;

public class VideoCollection
{
    private DataColumn colCategoryID;
    private DataColumn colCategory;

    private DataColumn colDirectorID;
    private DataColumn colDirector;

    private DataTable dtDirectors;

    public VideoCollection()
    {
        colCategoryID = new DataColumn("CategoryID");
        colCategory   = new DataColumn();
        colCategory.ColumnName = "Category";

        dtDirectors   = new DataTable();
        colDirectorID = dtDirectors.Columns.Add();
        colDirector   = dtDirectors.Columns.Add("Director");
    }
}

If you have already formally created a DataColumn object, to add it to the collection of columns of a table, call the following version of the DataColumnCollection.Add() method:

public void Add(DataColumn column);

This method expects a DataColumn object as argument. You can either primarily create a DataColumn value or you can define one in the parentheses of the method. Here are two examples:

using System;
using System.Data;

public class VideoCollection
{
    private DataColumn colCategoryID;
    private DataColumn colCategory;

    private DataColumn colDirectorID;
    private DataColumn colDirector;

    private DataTable dtDirectors;

    private DataTable dtVideos;
    private DataColumn colVideo;

    public VideoCollection()
    {
        colCategoryID = new DataColumn("CategoryID");
        colCategory = new DataColumn();
        colCategory.ColumnName = "Category";

        dtDirectors = new DataTable();
        colDirectorID = dtDirectors.Columns.Add();
        colDirector = dtDirectors.Columns.Add("Director");

        dtVideos = new DataTable("Videos");
        colVideo = new DataColumn("Video");
        dtVideos.Columns.Add(colVideo);
    }
}

Practical Learning Practical Learning: Creating Columns

  1. To create a few columns, change the file as follows:
     
    using System;
    using System.Data;
    
    namespace VideoCollection2
    {
        public class Video
        {
            private DataSet dsVideoCollection;
    
            private DataColumn colActorName;
            private DataColumn colDateOfBirth;
            private DataTable  tblActors;
    
            private DataTable tblVideos;
    
            public Video()
            {
                dsVideoCollection = new DataSet("VideoCollection");
    
                tblActors = new DataTable("Actors");
    
                colActorName = new DataColumn();
                colActorName.ColumnName = "Actor Name";
                tblActors.Columns.Add(colActorName);
    
                colDateOfBirth = new DataColumn("Date of Birth");
                tblActors.Columns.Add(colDateOfBirth);
    
                dsVideoCollection.Tables.Add(tblActors);
    
                tblVideos = new DataTable("Videos");
                dsVideoCollection.Tables.Add(tblVideos);
            }
    
            public void ShowTables()
            {
                int i = 1;
    
                Console.WriteLine("Video Collection - Tables");
                foreach (DataTable tbl in dsVideoCollection.Tables)
                    Console.WriteLine("{0}. {1}", i++, tbl.TableName);
            }
        }
    }
  2. Save the file

Adding an Array of Columns

Instead of adding one column (at a time) to a table, you can first create an array of columns and add that array to the collection of columns. To do this, you can call the DataColumnCollection.AddRange() method. Its syntax is:

public void AddRange(DataColumn[] columns);

This method takes as argument an array of predefined columns. Here is an example:

using System;
using System.Data;

public class VideoCollection
{
    private DataTable dtVideos;
    private DataColumn[] colVideos;
    private DataSet dsVideoCollection;

    public VideoCollection()
    {
        dsVideoCollection = new DataSet("Video");
        dtVideos = new DataTable("Video");

        colVideos = new DataColumn[7];

        colVideos[0] = new DataColumn("Title");
        colVideos[1] = new DataColumn("Director");
        colVideos[2] = new DataColumn("YearReleased");
        colVideos[3] = new DataColumn("Length");
        colVideos[4] = new DataColumn("Rating");
        colVideos[5] = new DataColumn("Format");
        colVideos[6] = new DataColumn("Category");

        dtVideos.Columns.AddRange(colVideos);

        dsVideoCollection.Tables.Add(dtVideos);
    }
}

Specifying the Type of Data of a Column

If you create an application that allows the user to enter some values for the above list of videos, you would wish the user enter the right type of data under each column. To assist you with, the DataColumn class allows you to specify an appropriate or desired data type for each column. Just as done in other regular applications, the data types of a table allow its columns to accept or reject inappropriate values. Although we saw that the name was the most important aspect of a column, in reality, a data type is also required.

To supports data types for a column, the DataColumn class relies on the following .NET Framework structures we have used in previous lessons: Boolean, Byte , Char, DateTime, Decimal, Double, Int16, Int32, Int64, SByte, Single, String, TimeSpan, UInt16, UInt32, and UInt64. The DataColumn class can also support an array of Byte values, as in Byte[], for a column.

When creating a new column, if you don't specify its data type, it is assumed to be a string and the string data type is automatically applied to it. To specify the data type of a column, you have two main alternatives. When declaring a column, to specify its data type, you can initialize the DataColumn variable using the third constructor of the class. Its syntax is:

public DataColumn(string columnName, Type dataType);

To specify a column's data type, select one from the Type class of the System namespace by calling the Type.GetType() method. The GetType() method is overloaded with three versions. The first version has the following syntax:

public static Type GetType(string typeName);

This method expects as argument a valid data type defined in the .NET Framework. The data type must be retrieved from the Type class of the System namespace. The name of the data type must be qualified with a period operator. Here is an example:

using System;
using System.Data;

public class VideoCollection
{
    private DataColumn colCategoryID;

    public VideoCollection()
    {
        colCategoryID = new DataColumn("CategoryID", Type.GetType("System.Int32"));
    }
}

If you used the default constructor to declare a DataColumn, to specify its data type, assign its qualified type to the DataColumn.DataType property. Here is an example:

using System;
using System.Data;

public class VideoCollection
{
    private DataColumn colCategoryID;
    private DataColumn colCategory;

    public VideoCollection()
    {
        colCategoryID = new DataColumn("CategoryID", Type.GetType("System.Int32"));

        colCategory = new DataColumn();
        colCategory.ColumnName = "Category";
        colCategory.DataType = Type.GetType("System.String");
    }
}

Remember that there are various techniques you can use to create a column by specifying its name and its data type.

Practical Learning Practical Learning: Specifying the Data Types of Columns Columns

  1. To create columns with data types and specify the data types of existing columns, change the Video.cs file as follows:
     
    using System;
    using System.Data;
    
    namespace VideoCollection2
    {
        public class Video
        {
            private DataSet dsVideoCollection;
    
            private DataColumn colActorName;
            private DataColumn colDateOfBirth;
            private DataTable tblActors;
    
            private DataColumn colTitle;
            private DataColumn colDirector;
            private DataColumn colLength;
            private DataColumn colFormat;
            private DataColumn colRating;
            private DataTable tblVideos;
    
            public Video()
            {
                dsVideoCollection = new DataSet("VideoCollection");
    
                tblActors = new DataTable("Actors");
    
                colActorName = new DataColumn();
                colActorName.ColumnName = "Actor Name";
                colActorName.DataType   = Type.GetType("System.String");
                tblActors.Columns.Add(colActorName);
    
                colDateOfBirth = new DataColumn("Date of Birth",
                                                Type.GetType("System.DateTime"));
                tblActors.Columns.Add(colDateOfBirth);
    
                dsVideoCollection.Tables.Add(tblActors);
    
                tblVideos = new DataTable("Videos");
    
                colTitle = new DataColumn("Title", Type.GetType("System.String"));
                tblVideos.Columns.Add(colTitle);
    
                colDirector = new DataColumn("Director",
                                             Type.GetType("System.String"));
                tblVideos.Columns.Add(colDirector);
    
                colLength = new DataColumn("Length",
                                           Type.GetType("System.String"));
                tblVideos.Columns.Add(colLength);
    
                colFormat = new DataColumn("Format",
                                           Type.GetType("System.Int16"));
                tblVideos.Columns.Add(colFormat);
    
                colRating = new DataColumn("Rating",
                                           Type.GetType("System.Byte"));
                tblVideos.Columns.Add(colRating);
    
                dsVideoCollection.Tables.Add(tblVideos);
            }
    
            public void ShowTables()
            {
                int i = 1;
    
                Console.WriteLine("Video Collection - Tables");
                foreach (DataTable tbl in dsVideoCollection.Tables)
                    Console.WriteLine("{0}. {1}", i++, tbl.TableName);
            }
        }
    }
  2. Save the file

Columns Maintenance

 

Introduction

Column maintenance consists of adding one or more columns to a table, identifying an existing column in a table, looking for a column in a table, deleting one column or deleting all columns of a table. All these operations are easily supported by the various classes of the System.Data namespace.

The Parent Table of a Column

You are probably now familiar with the relationships among the data set, the table and the columns. Just in case:

  1. A table belongs to a data set and not the contrary. Also, you can create and use a data set without creating a table
  2. A column must belong to a table. A table without at least one column is no table at all. It is useless

When using the information stored in a table we will learn when studying records, sometimes you will need to identify the table that owns a particular column you are accessing. This information can be provided by the Table property of the DataColumn class.

Identifying a Column

Once again, remember that the group of columns of a table is an object of type DataColumnCollection. The DataColumnCollection class implements the GetEnumerator() method of the IEnumerable interface. This allows you to enumerate the columns of a table using foreach.

Practical Learning Practical Learning: Listing the Columns of a table

  1. To be able to list the columns of a table, change the videos.cs file as follows:
     
    using System;
    using System.Data;
    
    namespace VideoCollection2
    {
        public class Video
        {
            private DataSet dsVideoCollection;
    
            private DataColumn colActorName;
            private DataColumn colDateOfBirth;
            private DataTable  tblActors;
    
            private DataColumn colTitle;
            private DataColumn colDirector;
            private DataColumn colLength;
            private DataColumn colFormat;
            private DataColumn colRating;
            private DataTable  tblVideos;
    
            public Video()
            {
                dsVideoCollection = new DataSet("VideoCollection");
    
                tblActors = new DataTable("Actors");
    
                colActorName = new DataColumn();
                colActorName.ColumnName = "Actor Name";
                colActorName.DataType   = Type.GetType("System.String");
                tblActors.Columns.Add(colActorName);
    
                colDateOfBirth = new DataColumn("Date of Birth",
                                        Type.GetType("System.DateTime"));
                tblActors.Columns.Add(colDateOfBirth);
    
                dsVideoCollection.Tables.Add(tblActors);
    
                tblVideos = new DataTable("Videos");
    
                colTitle = new DataColumn("Title",
    				Type.GetType("System.String"));
                tblVideos.Columns.Add(colTitle);
    
                colDirector = new DataColumn("Director",
                                     Type.GetType("System.String"));
                tblVideos.Columns.Add(colDirector);
    
                colLength = new DataColumn("Length",
                                     Type.GetType("System.String"));
                tblVideos.Columns.Add(colLength);
    
                colFormat = new DataColumn("Format",
                                     Type.GetType("System.Int16"));
                tblVideos.Columns.Add(colFormat);
    
                colRating = new DataColumn("Rating",
                                     Type.GetType("System.Byte"));
                tblVideos.Columns.Add(colRating);
    
                dsVideoCollection.Tables.Add(tblVideos);
            }
    
            public void ShowTables()
            {
                int i = 1;
    
                Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
                Console.WriteLine("Video Collection - Tables");
                Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    
                foreach (DataTable tbl in dsVideoCollection.Tables)
                    Console.WriteLine("{0}. {1}", i++, tbl.TableName);
                Console.WriteLine("----------------------------");
            }
    
            public void ShowColumns(string table)
            {
                int i = 1;
                DataTable tbl = dsVideoCollection.Tables[table];
    
                Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
                Console.WriteLine("Video Collection - {0} Columns", table);
                Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    
                foreach (DataColumn col in tbl.Columns)
                    Console.WriteLine("{0}. {1}", i++, col.ColumnName);
                Console.WriteLine("----------------------------");
            }
        }
    }
  2. give the user the ability to choose, access the Program.cs file and change it as follows:
     
    using System;
    
    namespace VideoCollection2
    {
        public class Program
        {
            static int Main(string[] args)
            {
                char answer = 'q';
                char choiceTable = '0';
                Video vdo = new Video();
    
                do
                {
                    try
                    {
                        Console.WriteLine("\nWhat do you want to do?");
                        Console.WriteLine("1. Show the tables");
                        Console.WriteLine("2. Show the columns of a table");
                        Console.WriteLine("0. Quit");
                        Console.Write("Your Choice: ");
                        answer = char.Parse(Console.ReadLine());
                        Console.WriteLine("=========================\n");
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("Invalid Choice!");
                    }
    
                    switch (answer)
                    {
                        case '1':
                            vdo.ShowTables();
                            break;
                        case '2':
                            Console.WriteLine("Here are the available tables");
                            vdo.ShowTables();
    
                            try
                            {
        Console.Write("Enter the table whose columns you want to review: ");
                                choiceTable = char.Parse(Console.ReadLine());
                            }
                            catch (FormatException)
                            {
                                Console.WriteLine("Invalid answer!");
                            }
                            if (choiceTable == '1')
                                vdo.ShowColumns("Actors");
                            else if (choiceTable == '2')
                                vdo.ShowColumns("Videos");
                            break;
    
                        default:
                            break;
                    }
                } while((answer == '1') ||
                        (answer == '2'));
    
                return 0;
            }
        }
    }
  3. Execute the application and test it:
     
    What do you want to do?
    1. Show the tables
    2. Show the columns of a table
    0. Quit
    Your Choice: 1
    =========================
    
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    Video Collection - Tables
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    1. Actors
    2. Videos
    ----------------------------
    
    What do you want to do?
    1. Show the tables
    2. Show the columns of a table
    0. Quit
    Your Choice: 2
    =========================
    
    Here are the available tables
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    Video Collection - Tables
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    1. Actors
    2. Videos
    ----------------------------
    Enter the table whose columns you want to review: 2
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    Video Collection - Videos Columns
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    1. Title
    2. Director
    3. Length
    4. Format
    5. Rating
    ----------------------------
    
    What do you want to do?
    1. Show the tables
    2. Show the columns of a table
    0. Quit
    Your Choice: 0
    =========================
    
    Press any key to continue . . .
  4. Close the DOS window

Deleting Columns

 

Deleting a Column by Name

If you happen to have an undesired column in a table, you can delete it. To perform this operation, the DataColumnCollection class provides the Remove() method. This method is overloaded in two versions. One of them uses the following syntax:

public void Remove(string name);

This method expects the name of a column as argument. If the table has that column, the column would be deleted. Here is an example:

using System;
using System.Data;

namespace VideoCollection
{
    public static  class Program
    {
        static DataSet dsVideos;

        static DataColumn colTitle;
        static DataColumn colDirector;
        static DataColumn colLength;
        static DataColumn colFormat;
        static DataColumn colRating;
        static DataTable tblVideos;

        static void CreateCollection()
        {
            dsVideos = new DataSet("Videos");

            tblVideos = new DataTable("Video");

            colTitle = new DataColumn("Title", Type.GetType("System.String"));
            tblVideos.Columns.Add(colTitle);

            colDirector = new DataColumn("Director",
                                         Type.GetType("System.String"));
            tblVideos.Columns.Add(colDirector);

            colLength = new DataColumn("Length",
                                       Type.GetType("System.String"));
            tblVideos.Columns.Add(colLength);

            colFormat = new DataColumn("Format",
                                       Type.GetType("System.Int16"));
            tblVideos.Columns.Add(colFormat);

            colRating = new DataColumn("Rating",
                                       Type.GetType("System.Byte"));
            tblVideos.Columns.Add(colRating);

            dsVideos.Tables.Add(tblVideos);
        }


        static  void ShowTables()
        {
            int i = 1;

            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Console.WriteLine("Video Collection - Tables");
            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");

            foreach (DataTable tbl in dsVideos.Tables)
                Console.WriteLine("{0}. {1}", i++, tbl.TableName);
            Console.WriteLine("----------------------------");
        }

        static  void ShowColumns(string table)
        {
            int i = 1;
            DataTable tbl = dsVideos.Tables[table];

            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Console.WriteLine("Video Collection - {0} Columns", table);
            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");

            foreach (DataColumn col in tbl.Columns)
                Console.WriteLine("{0}. {1}", i++, col.ColumnName);
            Console.WriteLine("----------------------------");
        }

        static int Main(string[] args)
        {
            CreateCollection();

            int i = 1;
            DataTable tbl = dsVideos.Tables["Video"];

            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Console.WriteLine("Video Collection\nColumns of the Video table");
            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");

            foreach (DataColumn col in tbl.Columns)
                Console.WriteLine("{0}. {1}", i++, col.ColumnName);
            Console.WriteLine("----------------------------");

            tbl.Columns.Remove("Length");

            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Console.WriteLine("Video Collection\nColumns of the Video table");
            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");

            i = 1;
            foreach (DataColumn col in tbl.Columns)
                Console.WriteLine("{0}. {1}", i++, col.ColumnName);
            Console.WriteLine("----------------------------");

            return 0;
        }
    }
}

This would produce:

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Video Collection
Columns of the Video table
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
1. Title
2. Director
3. Length
4. Format
5. Rating
----------------------------
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Video Collection
Columns of the Video table
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
1. Title
2. Director
3. Format
4. Rating
----------------------------
Press any key to continue . . .

If there is no column with the name passed as argument to the DataColumnCollection.Remove() method, the compiler would throw an ArgumentException exception. As this can only be undesirable, the DataColumnCollection class allows you to check the existence of the column on the table. This is done by calling the Contains() method whose syntax is:

public bool Contains(string name);

Here is an example of calling it:

using System;
using System.Data;

namespace VideoCollection
{
    public static  class Program
    {
        . . . No Change

        static int Main(string[] args)
        {
            CreateCollection();

            int i = 1;
            DataTable tbl = dsVideos.Tables["Video"];

            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Console.WriteLine("Video Collection\nColumns of the Video table");
            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");

            foreach (DataColumn col in tbl.Columns)
                Console.WriteLine("{0}. {1}", i++, col.ColumnName);
            Console.WriteLine("----------------------------");

            if (tbl.Columns.Contains("Length"))
            {
                tbl.Columns.Remove("Length");

                Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
                Console.WriteLine("Video Collection\nColumns of the Video table");
                Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");

                i = 1;
                foreach (DataColumn col in tbl.Columns)
                    Console.WriteLine("{0}. {1}", i++, col.ColumnName);
                Console.WriteLine("----------------------------");
            }

            return 0;
        }
    }
}

Even if the table contains that column, it may not allow the column to be be deleted. For this reason, you should first check that the table allows that the column be deleted. To assist you with checking this, the DataColumnCollection class is equipped with the CanRemove() method. Its syntax is:

public bool CanRemove(DataColumn column);

Deleting a Column by Index

The columns of a table are arranged in an indexed list with the first (the most left) column at index 0, the second (from left) at index 1, and so on. To delete a column based on its index, you can call the DataColumnCollection.RemoveAt() method. Its syntax is:

public void RemoveAt(int index);

The index of the column is passed to this method. When calling this method, make sure you pass a valid index that is an integer greater than or equal to 0 but less than the DataColumnCollection.Count - 1. Here is an example:

using System;
using System.Data;

namespace VideoCollection
{
    public static  class Program
    {
        . . . No Change

        static int Main(string[] args)
        {
            CreateCollection();

            int i = 1;
            DataTable tbl = dsVideos.Tables["Video"];

            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Console.WriteLine("Video Collection\nColumns of the Video table");
            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");

            foreach (DataColumn col in tbl.Columns)
                Console.WriteLine("{0}. {1}", i++, col.ColumnName);
            Console.WriteLine("----------------------------");

            tbl.Columns.RemoveAt(4);

            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
            Console.WriteLine("Video Collection\nColumns of the Video table");
            Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");

            i = 1;
            foreach (DataColumn col in tbl.Columns)
                Console.WriteLine("{0}. {1}", i++, col.ColumnName);
            Console.WriteLine("----------------------------");

            return 0;
        }
    }
}

If you pass a negative index of a number >= DataColumnCollection.Count, the compiler would throw an IndexOutOfRangeException exception. If you know the object name of the column, you can first get its index by calling the DataColumnCollection.IndexOf() method and then pass its returned value to the RemoveAt() method.

Clearing the Table of Columns

To delete all columns from a table, you can call the DataColumnCollection.Clear() method. Its syntax is:

public void Clear();

After this method has been called, all columns from the table are deleted.

 

Previous Copyright © 2008-2016, FunctionX, Inc. Next