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 Minutes", "VHS", and "R" constitute one row one record.

 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 pointer to DataTable. To initialize the variable, the DataTable class is equipped with three constructors. The default constructor allows you to create a table without giving more details, especially without formally naming it. Here is an example:

```System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)

{

DataTable *dtDirectors = new DataTable;

}```

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

```namespace WinTables1

{

. . . No Change

private:

/// <summary>

/// Required designer variable.

/// </summary>

System::ComponentModel::Container * components;

DataSet *dsVideoCollection;

DataTable *dtDirectors;

. . . No Change

System::Void Form1_Load(System::Object *  sender, System::EventArgs *  e)

{

dsVideoCollection = new DataSet(S"Videos");

dtDirectors = new DataTable;

}```

The name of the DataTable variable is required when creating a table. This name will be used by you and the compiler to identify the table. In some cases, you may want the table to hold an object name that you would want to use later on as we will see with some methods. To provide a formal name to a table when creating it, you can use the second constructor of the DataTable class. Its syntax is:

`public: DataTable(String* tableName);`

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

```private:

DataSet *dsVideoCollection;

DataTable *dtVideoCategories;

DataTable *dtDirectors;

. . . No Change

System::Void Form1_Load(System::Object *  sender, System::EventArgs *  e)

{

dsVideoCollection = new DataSet(S"Videos");

dtVideoCategories = new DataTable(S"Categories");

dtDirectors = new DataTable();

}```

If you have already declared a DataTable variable using either of both constructors and decide to specify or change its name, you can assign a string to the DataTable::TableName property. Here is an example:

```System::Void Form1_Load(System::Object *  sender, System::EventArgs *  e)

{

dsVideoCollection = new DataSet(S"Videos");

dtVideoCategories = new DataTable(S"Categories");

dtDirectors = new DataTable();

dtDirectors->TableName = S"Directors";

}```

The TableName name is primarily optional but it is used by various methods as we will see. If you don't provide it, for example if you declare a DataTable variable using the default constructor and don't specify its name through the DataTable::TableName property, the compiler would generate a default name for the table, such as Table1, Table2, and so on.

In the same way, you can create as many tables as you judge necessary for your application and as we will see when moving on. After creating a table, you can add it to a DataSet object. 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 is a class that provides everything you need to add, locate, or manage any table that belongs to a DataSet.

Using the DataSet::Tables property, to add a created table to a DataSet, 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:

```private:

DataSet *dsVideoCollection;

DataTable *dtVideoCategories;

DataTable *dtDirectors;

DataTable *dtRatings;

. . . No Change

System::Void Form1_Load(System::Object *  sender, System::EventArgs *  e)

{

dsVideoCollection = new DataSet(S"Videos");

dtVideoCategories = new DataTable(S"Categories");

dtDirectors = new DataTable();

dtDirectors->TableName = S"Directors";

}```

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:

```System::Void Form1_Load(System::Object *  sender, System::EventArgs *  e)

{

dsVideoCollection = new DataSet(S"Videos");

dtVideoCategories = new DataTable(S"Categories");

dtDirectors = new DataTable();

dtDirectors->TableName = S"Directors";

}```

This second version of the method requires that you create a DataTable object first and the table probably have 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 object name of the new table. Here are examples:

```private:

DataSet *dsVideoCollection;

DataTable *dtVideoCategories;

DataTable *dtDirectors;

DataTable *dtRatings;

DataTable *dtActors;

DataTable *dtFormats;

. . . No Change

System::Void Form1_Load(System::Object *  sender, System::EventArgs *  e)

{

dsVideoCollection = new DataSet(S"Videos");

dtVideoCategories = new DataTable(S"Categories");

dtDirectors = new DataTable();

dtDirectors->TableName = S"Directors";

}```

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 class 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:

```System::Void btnTables_Click(System::Object *  sender, System::EventArgs *  e)

{

DataSet *dsBooks = new DataSet(S"Books");

DataTable *dtCategories = new DataTable(S"Categories");

DataTable *dtAuthors    = new DataTable(S"Authors");

DataTable *dtPublishers = new DataTable(S"Publishers");

DataTable *dtBooks      = new DataTable(S"Books");

DataTable *colTables[] = { dtCategories, dtAuthors, dtPublishers, dtBooks };

}```

While it is perfectly possible to programmatically create a table, the Visual Studio .NET programming environment provides graphical means of creating a table, without guessing. This allows you to visually set the characteristics of the table and let Visual Studio .NET write the code for you. As mentioned already, the tables of a DataSet object are stored in its Tables properties. In the same way, the Properties window provides the Tables field that allows you to visually create the tables.

 Practical Learning: Creating Tables
1. Under the form, click dsMusicStore if necessary. In the Properties window, click the Tables field to reveal its ellipsis button
2. Click the ellipsis button
3. In the Tables Collection Editor, click the Add button
4. While Table1 is selected in the Members list, in the Table1 Properties list, click (Name) and type tblCategories
5. Click TableName and type Categories

6. Click the Add button again
7. While Table1 is selected in the Members list, in the Table1 Properties list, click (Name) and type tblItemTypes
8. Click TableName and type ItemTypes
9. Click the Add button again
10. While Table1 is selected in the Members list, in the Table1 Properties list, click (Name) and type tblAvailableItems
11. Click TableName and type AvailableItems

12. Click Close
 Locating 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 property that ships in two versions. To locate a table using its name, use the following version of this property:

`public: __property DataTable *get_Item(String *name);`

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

```System::Void btnTable_Click(System::Object *  sender, System::EventArgs *  e)

{

DataTable *tbl = this->dsVideoCollection->Tables->Item[S"Directors"];

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::Item[] property. Its syntax is:

`public: __property DataTable *get_Item(int index);`

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

```System::Void btnTable_Click(System::Object *  sender, System::EventArgs *  e)

{

DataTable *tbl = this->dsVideoCollection->Tables->Item[2];

Text = tbl->TableName;

}```

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 two versions. One of the versions takes as argument the variable name of the table. The syntax of this method is:

`public: virtual int IndexOf(DataTable* table);`

Here is an example of calling this method:

```System::Void btnTable_Click(System::Object *  sender, System::EventArgs *  e)

{

int index = this->dsVideoCollection->Tables->IndexOf(this->dtVideos);

Text = index.ToString();

}```

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* name);`

When the tables of a DataSet have been created, you can get their list as an array using the DataTableCollection::List property. This property returns an ArrayList type of list.

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 of a table as argument. If the table exists in the collection, this method returns true. Here is an example:

```System::Void btnTable_Click(System::Object *  sender, System::EventArgs *  e)

{

if( this->dsVideoCollection->Tables->Contains(S"Actors") )

Text = S"The Actors table exists";

else

Text = S"Unknown Table";

}```

 Removing Tables

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 locate a table using its variable declared name and delete it, you can use the following version:

`public: void Remove(DataTable* table);`

This version expects the 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:

```System::Void btnRemove_Click(System::Object *  sender, System::EventArgs *  e)

{

this->dsVideoCollection->Tables->Remove(this->dtFormats);

}```

When calling this method, if the DataTable object passed as argument is not found, the compiler would throw either an ArgumentNullException or an ArgumentException exceptions. For this reason, before deleting a table, you should first check its existence by calling the DataTableCollection::Contains() method.

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. If no table with that name is found, the compiler would throw an ArgumentException exception. Once again, you should first check that a table with that name exists before deleting it.

To delete a table you created visually, in the Tables Collection Editor, click it in the Members list and click the Remove button

Besides checking the existence of a table, even if the table is found, 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);`

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

`public: void Clear();`

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