The Tables of a Data Set

 Tables Fundamentals

 Introduction to Tables

 Imagine you have a list of movie directors and you want to group their names into a list. Here is an example: Rob Reiner, Jonathan Lynn, Bruce Beresford, Jonathan Demme, Adrian Lyne

This is a one-dimensional list like a simple array. While working on this list, you may decide to create a video collection and make the above items into a formal list. A typical movie provides such information as its length, its rating, the year it was released, etc. To create such a list, you would group items by categories. One category may contain the titles of the videos. Another category may contain the names of the directors, and so on.

To better organize a list, you may create each category, then enter the value of each category that corresponds to a particular video. Here is an example:

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

This type of list is called a table: A table is a two-dimensional list that contains one or different categories of items and each category is represented with a particular value. A category of values is called a column. Under each category, you may have a group of values that belong to the same entry. Such a group of values is called a row or a record. In the above table, the values "A Few Good Men", "Rob Reiner", "1992", "138 Minute", "VH", and "R" constitute one row or record.

 The Tables of a Data Set

In our introduction, we defined a data set as one or more lists considered in a single group. Reversely, one or more lists grouped in a single entity is called a data set. In such a scenario, each list is created as a table, made of categories of values. Put in reverse, a data set is one or more tables used in one database.

 Creating a Table

 Programmatically Creating a Table

To support the creation and management of a table, the .NET Framework provides the DataTable class that is defined in the System.Data namespace. There are various ways you can create a table. You can declare a variable of type DataTable. To initialize the variable, the DataTable class is equipped with four constructors. The default constructor allows you to create a table without giving more details, especially without formally naming it. Here is an example:

```namespace VideoCollection1
{
public partial class Exercise : Form
{
DataSet dsVideoCollection;

public Exercise()
{
InitializeComponent();
}

private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

DataTable tblDirectors = new DataTable();
}
}
}```

If you are planning to refer to the table from more than one method, you should declare it globally. Here is an example:

```namespace VideoCollection1
{
public partial class Exercise : Form
{
DataSet dsVideoCollection;
DataTable tblDirectors;

public Exercise()
{
InitializeComponent();
}

private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
}
}
}```

When creating a table, you must name it; that is, you must give it an object name. To support the name of a table, the DataTable class is equipped with a property named TableName. To specify the name of a table, you can assign a string to it. Here is an example:

```private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";
}```

To specify the name of a table when creating it, you can use the following constructor of the DataTable class:

`public DataTable(string tableName);`

This constructor expects as argument a string that would constitute the object name of the table. Here is an example:

```public partial class Exercise : Form
{
DataSet dsVideoCollection;
DataTable tblDirectors;
DataTable tblVideoCategories;

public Exercise()
{
InitializeComponent();
}

private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";

tblVideoCategories = new DataTable("Categories");
}
}```

After creating a table, you can add it to a DataSet object.

 Visually Creating a Table

To visually create a table, under the form, you can click the data set object. In the Properties window, you can click Tables and click the ellipsis button of its field. This would open the Table Collection Editor. To create a table, you can click the Add button. A table would be added:

The new table has a default variable name under Members and an object name. To change the variable name, under the Properties list, you can click (Name) and type the desired name. To change the object name, you can click TableName and type the new name.

 Creating Tables in a Collection

 Introduction

The tables that belong to a DataSet object are stored in a property called Tables. The DataSet.Tables property is an object of type DataTableCollection. The DataTableCollection class is derived from a class named InternalDataCollectionBase. DataTableCollection is a class that provides everything you need to add, locate, or manage any table that belongs to a DataSet object.

While performing an operation such as adding a new table to the collection, the DataTableCollection class fires a CollectionChanging event. The syntax of this event is:

`public event CollectionChangeEventHandler CollectionChanging`

You cannot visually generate this event in Microsoft Visual Studio. If you want to catch it, you must manually define it. Here is an example:

```using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace VideoCollection1
{
public partial class Exercise : Form
{
DataTable tblDirectors;
DataTable tblVideoCategories;
DataSet dsVideoCollection;

public Exercise()
{
InitializeComponent();

dsVideoCollection = new DataSet("Videos");

dsVideoCollection.Tables.CollectionChanged +=
new CollectionChangeEventHandler(TableCollectionHasChanged);
}

private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";

tblVideoCategories = new DataTable("Categories");
}

void TableCollectionHasChanged(object sender, CollectionChangeEventArgs e)
{
MessageBox.Show("The list of tables has been changed");
}
}
}```

As you can see, this event is based on the CollectionChangeEventArgs class. The CollectionChangeEventArgs class has two properties. The Action property specifies what happened to the collection. This property is of type CollectionChangeAction, which is an enumeration. If a new table is being added, then the action is Add.

The CollectionChangeEventArgs class is also equipped with a property named Element, which is of type object. This property holds a DataTableCollection object with the current changes.

 Adding a New Table to a Collection

Using the DataSet.Tables property, to add a created table to a DataSet object, call one of the Add() methods of the DataTableCollection class. The first version of this method has the following syntax:

`public virtual DataTable Add();`

This method can be used to add a new table that uses the default name. Here is an example:

```namespace VideoCollection1
{
public partial class Exercise : Form
{
DataTable tblRatings;
DataTable tblDirectors;
DataTable tblVideoCategories;
DataSet dsVideoCollection;

public Exercise()
{
InitializeComponent();
}

private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";
tblVideoCategories = new DataTable("Categories");

}
}
}```

If this is the first table added to the collection, it would be named Table1. The second version of the DataTableCollection.Add() method uses the following syntax:

`public virtual void Add(DataTable table);`

This version allows you to add a predefined or declared DataTable object. Here is an example:

```namespace VideoCollection1
{
public partial class Exercise : Form
{
DataTable tblRatings;
DataTable tblDirectors;
DataTable tblVideoCategories;
DataSet dsVideoCollection;

public Exercise()
{
InitializeComponent();
}

private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";

tblVideoCategories = new DataTable("Categories");

}
}
}```

This second version of the method requires that you create a DataTable object first and the table probably has a name. Alternatively, if you want to add a table using its formal name, you can use the third version of this method. Its syntax is:

`public virtual DataTable Add(string name);`

This version works like the first except that, instead of the default name (such as Table1, Table2, etc), it lets you specify the desired name of the new table. Here are examples:

```namespace VideoCollection1
{
public partial class Exercise : Form
{
DataTable tblActors;
DataTable tblFormats;
DataTable tblRatings;
DataTable tblDirectors;
DataTable tblVideoCategories;
DataSet dsVideoCollection;

public Exercise()
{
InitializeComponent();
}

private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";

tblVideoCategories = new DataTable("Categories");

}
}
}```

When a new table has been created, the DataTableCollection class fires a CollectionChanged event. The syntax of this event is:

`public event CollectionChangeEventHandler CollectionChanged;`

Once again, you cannot visually generate this event. Instead, if you want to catch it, you must manually define it. Here is an example:

```using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace VideoCollection1
{
public partial class Exercise : Form
{
DataSet dsVideoCollection;

public Exercise()
{
InitializeComponent();

dsVideoCollection = new DataSet("Videos");

dsVideoCollection.Tables.CollectionChanged +=
new CollectionChangeEventHandler(TableCollectionHasChanged);
}

private void btnDocument_Click(object sender, EventArgs e)
{
}

void TableCollectionHasChanged(object sender, CollectionChangeEventArgs e)
{
}
}
}```

This event fires every time a new table is added to the collection. Here is an example:

```namespace VideoCollection1
{
public partial class Exercise : Form
{
DataTable tblActors;
DataTable tblFormats;
DataTable tblRatings;
DataTable tblDirectors;
DataTable tblVideoCategories;
DataSet dsVideoCollection;

public Exercise()
{
InitializeComponent();

dsVideoCollection = new DataSet("Videos");

dsVideoCollection.Tables.CollectionChanged +=
new CollectionChangeEventHandler(TableCollectionHasChanged);
}

private void btnDocument_Click(object sender, EventArgs e)
{
tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";

tblVideoCategories = new DataTable("Categories");

foreach (DataTable tbl in dsVideoCollection.Tables)
}

void TableCollectionHasChanged(object sender, CollectionChangeEventArgs e)
{
MessageBox.Show("The list of tables has been changed");
}

}
}```

This event also is based on the CollectionChangeEventArgs class. If a new table was added, then the action of the event is Add.

 Creating a Range of Tables

Instead of adding one table at a time, you can create a list of tables and then add it to the DataSet.Tables collection. To support this operation, the DataTableCollection is equipped with the AddRange() method. Its syntax is:

`public void AddRange(DataTable[] tables);`

This method expects an array of DataTable objects as argument. Here is an example:

```namespace BookCollection1
{
public partial class Exercise : Form
{
public Exercise()
{
InitializeComponent();
}

private void btnDocument_Click(object sender, EventArgs e)
{
DataSet dsBooks = new DataSet("Book");

DataTable dtCategories = new DataTable("Categorie");
DataTable dtAuthors = new DataTable("Author");
DataTable dtPublishers = new DataTable("Publisher");
DataTable dtBooks = new DataTable("Book");

DataTable[] colTables =
{ dtCategories, dtAuthors, dtPublishers, dtBooks };
}
}
}```
 Accessing a Table in the Collection

 The Index of a Table

After creating the tables that are part of an application, before performing any operation on a table, you must first retrieve its reference. This can be done by locating the particular desired table from the collection.

To locate a table in the DataSet.Tables collection, the DataTableCollection class is equipped with the Item indexed property in three versions. To locate a table using its name, use the following version of this property:

`public DataTable this[string name] {get;}`

To use this property, enter the object name of the table in the square brackets of the DataTableCollection[] property. Here is an example:

```namespace VideoCollection1
{
public partial class Exercise : Form
{
DataTable tblActors;
DataTable tblFormats;
DataTable tblRatings;
DataTable tblDirectors;
DataTable tblVideoCategories;
DataSet dsVideoCollection;

public Exercise()
{
InitializeComponent();
}

private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";

tblVideoCategories = new DataTable("Categories");

DataTable tbl = dsVideoCollection.Tables["Directors"];

txtVideo.Text = tbl.TableName;
}
}
}```

Instead of locating a table by its name, you can use its index from the collection. To do this, you can use the second version of the DataTableCollection[] property. Its syntax is:

`public DataTable this[int index] {get;}`

This property expects as argument the index of the table in the DataSet.Tables collection. Here is an example:

```private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";

tblVideoCategories = new DataTable("Categories");

DataTable tbl = dsVideoCollection.Tables[3];

txtVideo.Text = tbl.TableName;
}```

This would produce Actors.

 For Each

The InternalDataCollectionBase class, the parent of DataTableCollection, implements the GetEnumerator() method of the IEnumerable interface. This allows you to use a foreach loop to visit each member table of the collection. Once you have reached a table in the collection, you can access any of its public properties or methods. Here is an example of applying foreach on a collection of tables of a data set to list their names:

```namespace VideoCollection1
{
public partial class Exercise : Form
{
DataTable tblActors;
DataTable tblFormats;
DataTable tblRatings;
DataTable tblDirectors;
DataTable tblVideoCategories;
DataSet dsVideoCollection;

public Exercise()
{
InitializeComponent();
}

private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";

tblVideoCategories = new DataTable("Categories");

foreach (DataTable tbl in dsVideoCollection.Tables)
}
}
}```

This would produce:

You can use this approach to identity a table and then perform a desired operation on it.

 Locating a Table in a Collection

 The Index of a Table

When using the DataTable this[int index] indexed property, if you provide an index below or beyond the number of tables in the set, the compiler would throw an IndexOutOfRangeException exception. To avoid this, you can request the index of the table. To do this, call the DataTableCollection.IndexOf() method. It is overloaded in three versions. One of the versions uses the following syntax:

`public virtual int IndexOf(DataTable table);`

This version takes as argument the variable name of the table. Here is an example of calling this method:

```private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";

tblVideoCategories = new DataTable("Categories");

int index = dsVideoCollection.Tables.IndexOf(tblActors);
txtVideo.Text = index.ToString();
}```

This would produce 3

Instead of using the variable name of the table, you can locate it using its formal name. To do this, call the following version of the IndexOf() method:

`public virtual int IndexOf(string tableName);`
 Checking the Existence of a Table

Instead of directly locating a table, you may be interested to know whether a particular table exists in the DataSet.Tables collection. To check this, you can call the DataTableCollection.Contains() method. Its syntax is:

`public bool Contains(string name);`

This method expects the object name (not the variable name) of a table as argument. If the table exists in the collection, this method returns true. Here is an example:

```private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";

tblVideoCategories = new DataTable("Categories");

if (dsVideoCollection.Tables.Contains("Actors"))
MessageBox.Show("The Actors table exists");
else
MessageBox.Show("The Actors table does not exist");

if (dsVideoCollection.Tables.Contains("VideoTypes"))
MessageBox.Show("The VideoTypes table exists");
else
MessageBox.Show("The VideoTypes table does not exist");
}```

This would produce:

 Tables Maintenance

 Deleting a Table

If you happen to have a table you don't need anymore or whose role is undefined in your application, you can delete that table. This operation is supported by the DataTableCollection.Remove() method that is overloaded with two versions. To delete a table using its variable declared name, you can use the following version:

`public void Remove(DataTable table);`

This version expects the variable name that was used to declare the DataTable object. If the table exists in the DateSet.Tables collection, it would be deleted. Here is an example:

```private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";

tblVideoCategories = new DataTable("Categories");

foreach (DataTable tbl in dsVideoCollection.Tables)

dsVideoCollection.Tables.Remove(tblVideoCategories);

foreach (DataTable tbl in dsVideoCollection.Tables)
}```

This would produce:

To delete a table using its object name, you can use the following version of the DataTableCollection.Remove() method:

`public void Remove(string name);`

This method expects the formal name of the table as argument. If a table exists under that name, it would be deleted. Here is an example:

```private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";

tblVideoCategories = new DataTable("Categories");

foreach (DataTable tbl in dsVideoCollection.Tables)

dsVideoCollection.Tables.Remove("Categories");

foreach (DataTable tbl in dsVideoCollection.Tables)
}```

If no table with the name is found, the compiler would throw an ArgumentException exception. Once again, you should first check that a table with the undesired name exists before deleting it.

If the table exists in the collection, it may not allow the user to delete it. To find out whether a table can be deleted, call the DataTableCollection.CanRemove() method. Its syntax is:

`public bool CanRemove(DataTable table);`

When calling the DataTableCollection.Remove() method, if the DataTable object passed as argument is not found, the compiler would throw either an ArgumentNullException or an ArgumentException exception. Here is an example:

```private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";

dsVideoCollection.Tables.Remove("Types");
}```

This would produce:

Therefore, before deleting a table, you should first check its existence. To do this, you can call the DataTableCollection.Contains() method.

Here is an example of calling this method before deleting a table:

```private void btnDocument_Click(object sender, EventArgs e)
{
dsVideoCollection = new DataSet("Videos");

tblDirectors = new DataTable();
tblDirectors.TableName = "Directors";

tblVideoCategories = new DataTable("Categories");

foreach (DataTable tbl in dsVideoCollection.Tables)

if (dsVideoCollection.Tables.Contains("Types"))
dsVideoCollection.Tables.Remove("Types");
else

foreach (DataTable tbl in dsVideoCollection.Tables)
}```

This would produce:

While deleting a table from the collection, the DataTableCollection fires a CollectionChanging event. After a table has been removed from the collection, the DataTableCollection fires a CollectionChanged event. As we saw earlier, both events are of type CollectionChangeEventArgs. While a table is being deleted or after it has been deleted, the action of this event is Remove.

 Clearing a Collection of Tables

To delete all tables of a DataSet object, you can call the DataTableCollection.Clear() method. Its syntax is:

`public void Clear();`

Calling this method would remove all DataTable objects of the DataSet.

When clearing the collection of all its tables, the DataTableCollection fires a CollectionChanging event. After the tables have been deleted, the DataTableCollection fires a CollectionChanged event. In both cases, the action of this event is Refresh.