Home

Databases Fundamentals: Data Records

 

Tables Records

 

Introduction to Records

In our description of tables, we saw that a table was made of one or various columns that represent categories of data. After creating such a table and its columns that represent the categories, you (actually the user) can enter values in the table to make it a valuable list. Filling up a table with values is referred to as data entry.

A record on a table is represented as a row (horizontal) of data. To support the various records that belong to a table, the DataTable class is equipped with a property called Rows. The DataTable.Rows property is in fact an object of the DataRowCollection class. The DataRowCollection class provides the necessary properties and methods you can use to create and manage records of a table. A row itself is an object based on the DataRow class.

 

Practical Learning Practical Learning: Introducing Data Records

  1. Start Notepad and type the following:
     
    using System;
    using System.IO;
    using System.Xml;
    using System.Data;
    
    namespace VideoCollection
    {
    	public class Video
    	{
    		public DataSet dsVideoCollection;
    
    		public Video()
    		{
    			dsVideoCollection = new DataSet("Videos");
    		}
    	}
    
    	class Exercise
    	{
    
    		public static int Main()
    		{
    			Video vdo = new Video();
    
    			return 0;
    		}
    	}
    }
  2. To save the file, on the main menu, click File -> Save
  3. Locate your CSharp Lessons folder and display it in the Save In combo box
  4. Click the Create New Folder button. Type VideoCollection3 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.cs and click Save
 

Introduction to Data Entry

When performing data entry and while doing it on a record, the record has a status that can be identify by the DataRow.RowState property which is a value based on the DataRowState enumerator.

A record on a table is represented as a row of data. To support the various records that belong to a table, the DataTable class is equipped with the Rows property which is an object of type DataRowCollection with each record being an object of type DataRow.

Before adding a new record to a table, you must let the table know. This is done by calling the DataTable.NewRow() method. Its syntax is:

public DataRow NewRow();

The DataTable.NewRow() method returns a DataRow object. Here is an example:

DataRow rowDirector = this.dtDirectors.NewRow();
 

Practical Learning Practical Learning: Introducing Data Entry

  1. To prepare for data display, change the file as follows:
     
    using System;
    using System.IO;
    using System.Xml;
    using System.Data;
    
    namespace VideoCollection
    {
    	public class Video
    	{
    		public DataSet dsVideoCollection;
    
    		public DataTable tblVideos;
    
    		public DataColumn colTitle;
    		public DataColumn colDirector;
    		public DataColumn colYear;
    		public DataColumn colRating;
    		public DataColumn colLength;
    
    		public Video()
    		{
    			dsVideoCollection = new DataSet("Videos");
    		}
    
    		public void ShowVideos(string strFilename)
    		{
    			if( File.Exists(strFilename) )
    			{
    				XmlDocument xmlPeople = new XmlDocument();
    				xmlPeople.Load(strFilename);
    				string[] rating = { "G", "PG", "PG-13", "R", "NC-17", "Not Rated or all audiences" };
    
    				XmlElement nodRoot = xmlPeople.DocumentElement;
    			 XmlNodeList nodTitles = nodRoot.GetElementsByTagName("Title");
    			 XmlNodeList nodDirectors = nodRoot.GetElementsByTagName("Director");
    			 XmlNodeList nodYears = nodRoot.GetElementsByTagName("Year");
    			 XmlNodeList nodRatings  = nodRoot.GetElementsByTagName("Rating");
    			 XmlNodeList nodLengths  = nodRoot.GetElementsByTagName("Length");
    
    			 	for(int i = 0; i < nodTitles.Count; i++)
    			 	{
    				 Console.WriteLine("Title:    {0}", nodTitles[i].InnerText);
    				 Console.WriteLine("Director: {0}", nodDirectors[i].InnerText);
    				 Console.WriteLine("Year:     {0}", nodYears[i].InnerText);
    				 Console.WriteLine("Rating:   {0}", rating[int.Parse(nodRatings[i].InnerText) - 1]);
    				 Console.WriteLine("Length:   {0}", nodLengths[i].InnerText);
    			 	}
    		 	}
    		}
    	}
    
    	class Exercise
    	{
    		public static int Main()
    		{
    			Video vdo = new Video();
    
    			// This is the file that will hold the records
    			string strFilename = "VideoCollection.xml";
    
    			// If that file exists already, open it
    			if( File.Exists(strFilename) )
    				vdo.dsVideoCollection.ReadXml(strFilename);
    			else // If it doesn't exist already, then create it
    				vdo.dsVideoCollection.WriteXml(strFilename);
    
    			return 0;
    		}
    	}
    }
  2. Save the file

Data Entry

 

Adding a Value Based on the Column Index

When you call the DataTable.NewRow() method, the record's status is DataRowState.Detached. After calling the DataTable.NewRow() method, you can specify the value that the column would carry. To do this, you must specify the table's column whose value you want to provide. You can locate a column based on an index as we mentioned already that the columns of a table are stored in the DataTable.Columns property which is based on the DataColumnCollection class. Each column can be identified by its index. 

When the record has been added to the table, the record has a status of DataRowState.Added. The above version of the DataRowCollection.Add() method allows you to add a value for one column. To complete a record, you would have to create a value for each column.

 

Practical Learning Practical Learning: Adding a Value Based on the Column Index

  1. To create a record using the column's indices, change the file as follows:
     
    using System;
    using System.IO;
    using System.Xml;
    using System.Data;
    
    namespace VideoCollection
    {
    	public class Video
    	{
    		public DataSet dsVideoCollection;
    		
    		private DataTable tblVideos;
    
    		private DataColumn colTitle;
    		private DataColumn colDirector;
    		private DataColumn colYear;
    		private DataColumn colRating;
    		private DataColumn colLength;
    
    		public Video()
    		{
    			colTitle = new DataColumn("Title", System.Type.GetType("System.String"));
    			colDirector = new DataColumn("Director", System.Type.GetType("System.String"));
    			colYear = new DataColumn("Year", System.Type.GetType("System.Int32"));
    			colRating = new DataColumn("Rating", System.Type.GetType("System.Byte"));
    			colLength = new DataColumn("Length", System.Type.GetType("System.String"));
    			
    			tblVideos = new DataTable("Videos");
    			tblVideos.Columns.Add(colTitle);
    			tblVideos.Columns.Add(colDirector);
    			tblVideos.Columns.Add(colYear);
    			tblVideos.Columns.Add(colRating);
    			tblVideos.Columns.Add(colLength);
    
    			dsVideoCollection = new DataSet("Videos");
    			dsVideoCollection.Tables.Add(tblVideos);
    		}
    
    		public void CreateVideo()
    		{
    			string Title, Director, Length;
    			int Year, Rating;
    
    			Console.WriteLine("Enter the following pieces of information about the video");
    			Console.Write("Title:    ");
    			Title = Console.ReadLine();
    			Console.Write("Director: ");
    			Director = Console.ReadLine();
    			Console.Write("Year Reeased: ");
    			Year = int.Parse(Console.ReadLine());
    			Console.WriteLine("Specify corresponding rating");
    			Console.WriteLine("1. - G");
    			Console.WriteLine("2. - PG");
    			Console.WriteLine("3. - PG-13");
    			Console.WriteLine("4. - R");
    			Console.WriteLine("5. - NC-17");
    			Console.WriteLine("6. - Not Rated or all audiences");
    			Console.Write("Your Choice? ");
    			Rating = int.Parse(Console.ReadLine());
    			Console.Write("Length (ex 118mins): ");
    			Length = Console.ReadLine();
    
    			DataRow rowVideo = this.tblVideos.NewRow();
    			rowVideo[0] = Title;
    			rowVideo[1] = Director;
    			rowVideo[2] = Year;
    			rowVideo[3] = Rating;
    			rowVideo[4] = Length;
    				
    			this.tblVideos.Rows.Add(rowVideo);
    			this.dsVideoCollection.WriteXml("VideoCollection.xml");
    		}
    
    		public void ShowVideos(string strFilename)
    		{
    			if( File.Exists(strFilename) )
    			{
    				XmlDocument xmlPeople = new XmlDocument();
    				xmlPeople.Load(strFilename);
    				string[] rating = { "G", "PG", "PG-13", "R", "NC-17", "Not Rated or all audiences" };
    
    				XmlElement nodRoot = xmlPeople.DocumentElement;
    				 XmlNodeList nodTitles = nodRoot.GetElementsByTagName("Title");
    				 XmlNodeList nodDirectors = nodRoot.GetElementsByTagName("Director");
    				 XmlNodeList nodYears = nodRoot.GetElementsByTagName("Year");
    				 XmlNodeList nodRatings  = nodRoot.GetElementsByTagName("Rating");
    				 XmlNodeList nodLengths  = nodRoot.GetElementsByTagName("Length");
    
    				 for(int i = 0; i < nodTitles.Count; i++)
    				 {
    					 Console.WriteLine("Title:    {0}", nodTitles[i].InnerText);
    					 Console.WriteLine("Director: {0}", nodDirectors[i].InnerText);
    					 Console.WriteLine("Year:     {0}", nodYears[i].InnerText);
    					 Console.WriteLine("Rating:   {0}", rating[int.Parse(nodRatings[i].InnerText) - 1]);
    					 Console.WriteLine("Length:   {0}", nodLengths[i].InnerText);
    				 }
    		 	}
    		}
    	}
    
    	class Exercise
    	{
    		public static int Main()
    		{
    			Video vdo = new Video();
    
    			// This is the file that will hold the records
    			string strFilename = "VideoCollection.xml";
    
    			string choice = "0";
    
    			Console.WriteLine(" ### Main Menu ###");
    			Console.WriteLine("1. Register New Video");
    			Console.WriteLine("2. Show Video Collection");
    			Console.WriteLine("3. Quit");
    			Console.Write("Your Choice? ");
    			choice = Console.ReadLine();
    
    			// If that file exists already, open it
    			if( File.Exists(strFilename) )
    				vdo.dsVideoCollection.ReadXml(strFilename);
    			else // If it doesn't exist already, then create it
    				vdo.dsVideoCollection.WriteXml(strFilename);
    
    			if( choice == "1" )
    				vdo.CreateVideo();
    			else if( choice == "2" )
    				vdo.ShowVideos(strFilename);
    			else
    				Console.WriteLine("Good Bye");
    
    			return 0;
    		}
    	}
    }
  2. Save the file and open the Command Prompt
  3. Switch to the VideoCollection3 folder that contains the above file
  4. Compile the exercise by typing csc Exercise.cs and pressing Enter
  5. Execute the application by typing Exercise and pressing Enter
  6. Return to Notepad
 

Adding a Value Based on the Column Object Name

To specify the name of the column, the DataRow class is equipped with an index property that allows you to identify a column by its object name, by its variable name, or by its index. Based on this, the DataRow property is overloaded with three versions. One of the versions uses the following syntax:

public object this[string columnName] {get; set;}

This property expects the object name of the column passed in its square brackets. When calling this property, you can assign it the desired value for the column. Here is an example:

DataRow rowDirector = this.dtDirectors.NewRow();

rowDirector["Director"] = "John Landis";

After assigning the desired value to the row, to add the new value to a table, the DataRowCollection class provides the Add() method that is overloaded with two versions. The first version of this method uses the following syntax:

public void Add(DataRow row;

This method simply expects you to pass the DataRow object you previously defined. Here is an example:

DataRow rowDirector = this.dtDirectors.NewRow();

rowDirector["Director"] = "John Landis";
dtDirectors.Rows.Add(rowDirector);

In the same way, you can identify each column of a table by its object name and assign it the appropriate value. Once the record is complete, you can add it to the table. Here is an example:

void AddView()
{
	 DataRow rowVideo = this.dtVideos.NewRow();

	 rowVideo["Title"] = "A Few Good Men";
	 rowVideo["Director"] = "Rob Reiner";
	 rowVideo["YearReleased"] = 1993;
	 rowVideo["Length"] = "138 Minutes";
	 rowVideo["Rating"] = "R";
	 rowVideo["Format"] = "VHS";
	 rowVideo["Category"] = "Drama";
	 this.dtVideos.Rows.Add(rowVideo);
}

Adding an Array of Records

The above version of the DataRowCollection.Add() method means that you must identify each column before assigning a value to it. If you already know the sequence of columns and don't need to explicitly identify them, you can store all values in an array and simply add the array as a complete record. To do this, you can use the second version of the DataRowCollection.Add() method whose syntax is:

public virtual DataRow Add(object[] values);

Here is an example:

void AddNewVideo()
{
	 string[] vdoRecord = { "Fatal Attraction", "Adrian Lyne", "1987",
			       "120 Minute", "R", "DVD", "Drama" };

	 dtVideos.Rows.Add(vdoRecord);
}

There is an alternative to this second version of the DataRowCollection.Add() method. As opposed to passing an array of values to the Add() method, you can first define an array, assign that array to a DataRow variable, then pass that DataRow object to the Add() method. To support this technique, the DataRow class is equipped with an ItemArray property that expects an array. Here is an example

void AddNewVideo()
{
	 string[] vdoNewVideo = { "Her Alibi", "Bruce Beresford", "1989",
			             "94 Minute", "PG-13", "DVD", "Comedy" };
	 DataRow rowNewVideo = dtVideos.NewRow();
	 rowNewVideoArray = vdoNewVideo;
	 dtVideos.Rows.Add(rowNewVideo);
}

After creating the records of a table, if a record contains invalid values, the DataRow.HasErrors property can help you identify them.

Locating Records and Their Values

 

Locating a Record

Before performing any operation on a record, you must be able to locate it. That is, you must be able to identify a record among the various records of a table. To locate a record in the DataTable.Rows collection, the DataRowCollection class provides the Item property that is defined as follows

public DataRow this[int index] {get;}

The records of a table are stored in a list (called the DataRowCollection). The first record has an index of 0. The second record has an index of 1, and so on. Here is an example of using it to retrieve the information stored in a record:

DataRow row = this.dtVideos.Rows[2];

When you pass an index to this property, the compiler would check whether the record exists. If a record with that index exists, its DataRow value is produced. If you specify an index that is either less than 0 or beyond the number of records in the table, the compiler would throw an IndexOutOfRangeException exception.

To get the number of records that a table contains, access the Count property of its DataRowCollection. The Count property is inherited from the InternalDataCollectionBase class, which is the parent of many collection classes.

When the records of a DataTable object have been created, you can get their list as an array using its List property that is inherited from the InternalDataCollectionBase class. This property returns an ArrayList type of list.

 

Locating a Value

As mentioned already, a record is in fact one or a group of values from each of the columns of the table. Consider the following table:

The "A Few Good Men" string is a value of the Title column. In the same way, "VHS" is a value of the Format column. In some circumstances, you will need to locate a particular value in order to perform an operation on it. As seen above, you can start by locating the record you need and return its DataRow object. To know the table that the record belongs to, access its DataRow.Table property. This property is declared as follows:

public DataTable Table {get;}

To locate the value that a record holds under a particular column, the DataRow class provides the Item property that is overloaded with three versions (actually six, but at this time we are interested in the first three only). One of the versions of this property uses the following syntax:

public object this[string columnName] {get; set;}

To use this property, pass the object name of the column in the square brackets. Instead of using the index of a column, you can also locate a value using the variable name of its column. To do this, you can use the following syntax of the DataRow indexed property:

public object this[DataColumn column] {get; set;}

This property expects the object name of the column passed in its square brackets. The third option you have is to identify the column by its index. To do this, use the following syntax of the DataRow indexed property:

public object this[int columnIndex] {get; set;}

This property expects the index of the column.

 

Record Maintenance

Once a table has been filled with records, you can perform maintenance operations on it such as changing some records or removing others. To remove a record from a table, you can call the DataRowCollection.Remove() method. Its syntax is:

public void Remove(DataRow row);

This method takes as argument a DataRow object and checks whether the table contains. If that record exists, it gets deleted, including all of its entries for each column. When calling this method, you must pass an exact identification of the record. If you don't have that identification, you can delete a record based on its index. To do this, you would call the DataRowCollection.RemoveAt() method. Its syntax is:

public void RemoveAt(int index);

This method takes as argument the index of the record you want to delete. If a record with that index exists, it would be deleted.

To delete all records of a table, call the DataRowCollection.Clear() method. Its syntax is:

public void Clear();

This method is used to clear the table of all records.

 
 

Previous Copyright 2004-2005 FunctionX, Inc. Next