Home

Databases Fundamentals: Data Tables

 

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

Practical Learning Practical Learning: Introducing Tables

  1. Start Notepad and, in the empty document, type the following:
     
    Imports System
    Imports System.Xml
    Imports System.data
    
    Class Exercise
        Private Shared dsVideoCollection As DataSet
    
        Public Shared Sub Main()
    
            dsVideoCollection = New DataSet("Videos")
    
        End Sub
    
    End Class
  2. To save the file, on the main menu, click File -> Save
  3. Locate your VBasic folder and display it in the Save In combo box
  4. Click the Create New Folder button. Type VideoCollection1 and press Enter twice to display the new folder in the Save In combo box
  5. Change the Save As Type to All Files. Change the file name to Exercise.vb and click Save

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:

Imports System
Imports System.Data

Module Exercise

    Private dsVideoCollection As DataSet

    Sub Main()

        dsVideoCollection = New DataSet("Videos")
        Dim tblDirectors As DataTable = New DataTable
    End Sub

End Module

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:

Imports System
Imports System.Data

Module Exercise

    Private dsVideoCollection As DataSet
    Private tblDirectors As DataTable

    Sub Main()
        dsVideoCollection = New DataSet("Videos")
        tblDirectors = New DataTable
    End Sub

End Module

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 Sub New(ByVal tableName As String)

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

Imports System
Imports System.Data

Module Exercise

    Private dsVideoCollection As DataSet
    Private tblVideoCategories As DataTable
    Private tblDirectors As DataTable

    Sub Main()

        dsVideoCollection = New DataSet("Videos")
        tblDirectors = New DataTable

        tblVideoCategories = New DataTable("Categories")
    End Sub

End Module

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:

Imports System
Imports System.Data

Module Exercise

    Private dsVideoCollection As DataSet
    Private tblVideoCategories As DataTable
    Private tblDirectors As DataTable

    Sub Main()

        dsVideoCollection = New DataSet("Videos")
        tblDirectors = New DataTable
        tblDirectors.TableName = "Directors"

        tblVideoCategories = New DataTable("Categories")
    End Sub

End Module

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

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:

Overloads Public Overridable Function Add() As DataTable

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

Imports System
Imports System.Data

Module Exercise

    Private dsVideoCollection As DataSet
    Private tblVideoCategories As DataTable
    Private tblDirectors As DataTable
    Private tblRatings As DataTable

    Sub Main()

        dsVideoCollection = New DataSet("Videos")
        tblDirectors = New DataTable
        tblDirectors.TableName = "Directors"

        tblVideoCategories = New DataTable("Categories")

        tblRatings = dsVideoCollection.Tables.Add()
    End Sub

End Module

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:

Overloads Public Overridable Sub Add(ByVal table As DataTable)

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

Imports System
Imports System.Data

Module Exercise

    Private dsVideoCollection As DataSet
    Private tblVideoCategories As DataTable
    Private tblDirectors As DataTable
    Private tblRatings As DataTable

    Sub Main()

        dsVideoCollection = New DataSet("Videos")
        tblDirectors = New DataTable
        tblDirectors.TableName = "Directors"
        dsVideoCollection.Tables.Add(tblDirectors)

        tblVideoCategories = New DataTable("Categories")
        dsVideoCollection.Tables.Add(tblVideoCategories)

        tblRatings = dsVideoCollection.Tables.Add()
    End Sub

End Module

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:

Overloads Public Overridable Function Add(ByVal name As String) As DataTable

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:

Imports System
Imports System.Data

Module Exercise

    Private dsVideoCollection As DataSet
    Private tblVideoCategories As DataTable
    Private tblDirectors As DataTable
    Private tblRatings As DataTable
    Private tblActors As DataTable
    Private tblFormats As DataTable

    Sub Main()

        dsVideoCollection = New DataSet("Videos")
        tblDirectors = New DataTable
        tblDirectors.TableName = "Directors"
        dsVideoCollection.Tables.Add(tblDirectors)

        tblVideoCategories = New DataTable("Categories")
        dsVideoCollection.Tables.Add(tblVideoCategories)

        tblRatings = dsVideoCollection.Tables.Add()

        tblActors = dsVideoCollection.Tables.Add("Actors")
        tblFormats = dsVideoCollection.Tables.Add("Formats")
    End Sub

End Module

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 Sub AddRange(ByVal tables() As DataTable)

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

Private Sub Create()
        Dim dsBooks As DataSet = New DataSet("Book")

        Dim dtCategories As DataTable = New DataTable("Categories")
        Dim dtAuthors As DataTable = New DataTable("Authors")
        Dim dtPublishers As DataTable = New DataTable("Publishers")
        Dim dtBooks As DataTable = New DataTable("Book")

        Dim colTables() As DataTable = {dtCategories, dtAuthors, dtPublishers, dtBooks}
        dsBooks.Tables.AddRange(colTables)
End Sub
 

Practical Learning Practical Learning: Creating Tables

  1. To create tables, change the file as follows:
     
    Imports System
    Imports System.Xml
    Imports System.data
    
    Class Exercise
        Private Shared dsVideoCollection  As DataSet
    
        Private Shared tblVideoCategories As DataTable
        Private Shared tblDirectors       As DataTable
        Private Shared tblRatings         As DataTable
        Private Shared tblActors          As DataTable
        Private Shared tblFormats         As DataTable
    
        Public Shared Sub Main()
    
            dsVideoCollection = New DataSet("Videos")
    
    	tblDirectors = new DataTable()
    	tblDirectors.TableName = "Directors"
    	dsVideoCollection.Tables.Add(tblDirectors)
    
    	tblVideoCategories = new DataTable("Categories")
    	dsVideoCollection.Tables.Add(tblVideoCategories)
    
    	tblRatings = dsVideoCollection.Tables.Add()
    
    	tblActors = dsVideoCollection.Tables.Add("Actors")
    	tblFormats = dsVideoCollection.Tables.Add("Formats")
    		
        End Sub
    
    End Class
  2. Save the file

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:

Overloads Public Default ReadOnly Property Item(ByVal name As String) As DataTable

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

Imports System
Imports System.Data

Module Exercise

    Private dsVideoCollection As DataSet
    Private tblVideoCategories As DataTable
    Private tblDirectors As DataTable
    Private tblRatings As DataTable
    Private tblActors As DataTable
    Private tblFormats As DataTable

    Sub Main()

        dsVideoCollection = New DataSet("Videos")
        tblDirectors = New DataTable
        tblDirectors.TableName = "Directors"
        dsVideoCollection.Tables.Add(tblDirectors)

        tblVideoCategories = New DataTable("Categories")
        dsVideoCollection.Tables.Add(tblVideoCategories)

        tblRatings = dsVideoCollection.Tables.Add()

        tblActors = dsVideoCollection.Tables.Add("Actors")
        tblFormats = dsVideoCollection.Tables.Add("Formats")

        Dim tbl As DataTable = dsVideoCollection.Tables("Directors")
        Console.WriteLine("Table Name: {0}", tbl.TableName)
    End Sub

End Module

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:

Overloads Public Default ReadOnly Property Item(ByVal index As Integer) As DataTable

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

Imports System
Imports System.Data

Module Exercise

    Private dsVideoCollection As DataSet
    Private tblVideoCategories As DataTable
    Private tblDirectors As DataTable
    Private tblRatings As DataTable
    Private tblActors As DataTable
    Private tblFormats As DataTable

    Sub Main()

        dsVideoCollection = New DataSet("Videos")
        tblDirectors = New DataTable
        tblDirectors.TableName = "Directors"
        dsVideoCollection.Tables.Add(tblDirectors)

        tblVideoCategories = New DataTable("Categories")
        dsVideoCollection.Tables.Add(tblVideoCategories)

        tblRatings = dsVideoCollection.Tables.Add()

        tblActors = dsVideoCollection.Tables.Add("Actors")
        tblFormats = dsVideoCollection.Tables.Add("Formats")

        Dim tbl As DataTable = dsVideoCollection.Tables(1)
        Console.WriteLine("Table Name: {0}", tbl.TableName)
    End Sub

End Module

This would produce:

Table Name: Categories

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:

Overloads Public Overridable Function IndexOf(ByVal table As DataTable) As Integer

Here is an example of calling this method:

Imports System
Imports System.Data

Module Exercise

    Private dsVideoCollection As DataSet
    Private tblVideoCategories As DataTable
    Private tblDirectors As DataTable
    Private tblRatings As DataTable
    Private tblActors As DataTable
    Private tblFormats As DataTable

    Sub Main()

        dsVideoCollection = New DataSet("Videos")
        tblDirectors = New DataTable
        tblDirectors.TableName = "Directors"
        dsVideoCollection.Tables.Add(tblDirectors)

        tblVideoCategories = New DataTable("Categories")
        dsVideoCollection.Tables.Add(tblVideoCategories)

        tblRatings = dsVideoCollection.Tables.Add()

        tblActors = dsVideoCollection.Tables.Add("Actors")
        tblFormats = dsVideoCollection.Tables.Add("Formats")

        Dim index As Integer = dsVideoCollection.Tables.IndexOf(tblActors)
        Console.WriteLine("Table Index: {0}", index.ToString())
    End Sub

End Module

This would produce:

Table Index: 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:

Overloads Public Overridable Function IndexOf(ByVal tableName As String) As Integer

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 Function Contains(ByVal name As String) As Boolean

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:

Imports System
Imports System.Data

Module Exercise

    Private dsVideoCollection As DataSet
    Private tblVideoCategories As DataTable
    Private tblDirectors As DataTable
    Private tblRatings As DataTable
    Private tblActors As DataTable
    Private tblFormats As DataTable

    Sub Main()

        dsVideoCollection = New DataSet("Videos")
        tblDirectors = New DataTable
        tblDirectors.TableName = "Directors"
        dsVideoCollection.Tables.Add(tblDirectors)

        tblVideoCategories = New DataTable("Categories")
        dsVideoCollection.Tables.Add(tblVideoCategories)

        tblRatings = dsVideoCollection.Tables.Add()

        tblActors = dsVideoCollection.Tables.Add("Actors")
        tblFormats = dsVideoCollection.Tables.Add("Formats")

        If dsVideoCollection.Tables.Contains("Actors") Then
            Console.WriteLine("The Actors table exists")
        Else
            Console.WriteLine("Unknown Table")
        End If
    End Sub

End Module

This would produce:

The Actors table exists
 

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:

Overloads Public Sub Remove(ByVal table As DataTable)

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:

Imports System
Imports System.Data

Module Exercise

    Private dsVideoCollection As DataSet
    Private tblVideoCategories As DataTable
    Private tblDirectors As DataTable
    Private tblRatings As DataTable
    Private tblActors As DataTable
    Private tblFormats As DataTable

    Sub Main()

        dsVideoCollection = New DataSet("Videos")
        tblDirectors = New DataTable
        tblDirectors.TableName = "Directors"
        dsVideoCollection.Tables.Add(tblDirectors)

        tblVideoCategories = New DataTable("Categories")
        dsVideoCollection.Tables.Add(tblVideoCategories)

        tblRatings = dsVideoCollection.Tables.Add()

        tblActors = dsVideoCollection.Tables.Add("Actors")
        tblFormats = dsVideoCollection.Tables.Add("Formats")

        dsVideoCollection.Tables.Remove(tblVideoCategories)
    End Sub

End Module

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 as we saw above.

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

Overloads Public Sub Remove(ByVal name As String)

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.

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 Sub RemoveAt(ByVal index As Integer)

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

Public Sub Clear()

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

 
 

Previous Copyright © 2004-2012, FunctionX Next