Home

The ArrayList Class

 

Array Lists

 

Introduction

The main problem of traditional arrays is that their size is fixed by the number you specify when declaring the array variable: you cannot add items beyond the specified dimension. Another limitation is that you cannot insert an item inside the list. To overcome this, you can create a linked list. Instead of working from scratch, the .NET Framework provides the ArrayList class. With the ArrayList class, you can add new items to a list, insert items inside a list, arrange items of a list, check the existence of an item in a list, remove an item from the list, inquire about the list, or destroy the list. These operations are possible through various properties and methods.

The ArrayList class is defined in the System.Collections namespace. To use it, first declare a pointer to ArrayList. Here is an example:

private void Form1_Load(object sender, System.EventArgs e)
{
	ArrayList lstNumbers = new ArrayList();
}

 

Practical Learning Practical Learning: Introducing the ArrayList Class

  1. If you have not done so, create the StoreItem library now
  2. Start a new Windows Application named DepartmentStore2
  3. To add a library to this project, in the Solution Explorer, right-click References and click Add Reference...
  4. In the Add Reference dialog box, click Browse...
  5. Locate the folder that contains the StoreItem library and display it in the Look In combo box
  6. Double-click its bin folder and its Debug sub-folder to display it in the Look In combo box
     
  7. In the Select Component dialog box, select StoreItem.dll (it should be selected already) and click Open
  8. In the Add Reference dialog box, click OK
  9. Design the form as follows:
     
     
    Control Name Text Other Properties
    TabControl      
    TabPage pgeNewItem New Item  
    Label   Item #:  
    TextBox txtItemNumber    
    Label   Description:  
    TextBox txtDescription    
    Label   Size:  
    TextBox txtSize    
    Label   UnitPrice:  
    TextBox txtUnitPrice   TextAlign: Right
    Button btnAddItem Add Item  
    Label lblInventoryCount
    TabPage pgeInventory Store Inventory  
    DataGrid     AutoFormat: Colorful 1
    Button btnClose Close  
  10. Double-click the body of the form outside the tab control to access its Load event
  11. Change the file as follows:
     
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using StoreItem;
    
    namespace DepartmentStore2
    {
    	/// <summary>
    	/// Summary description for Form1.
    	/// </summary>
    	public class Form1 : System.Windows.Forms.Form
    	{
    		. . . No Change
    		
    		/// <summary>
    		/// Required designer variable.
    		/// </summary>
    		private System.ComponentModel.Container components = null;
    		ArrayList StoreItems;
    
    		. . . No Change
    
    		#region Windows Form Designer generated code
    		/// <summary>
    		/// Required method for Designer support - do not modify
    		/// the contents of this method with the code editor.
    		/// </summary>
    		private void InitializeComponent()
    		{
    			. . . No Change
    			
    		}
    		#endregion
    
    		/// <summary>
    		/// The main entry point for the application.
    		/// </summary>
    		[STAThread]
    		static void Main() 
    		{
    			Application.Run(new Form1());
    		}
    
    		private void Form1_Load(object sender, System.EventArgs e)
    		{
    			StoreItems = new ArrayList();
    
    			DateTime tmeNow = DateTime.Now;
    			int mls = tmeNow.Millisecond;
    			// Generate two random numbers between 100 and 999
    			Random rndNumber = new Random(mls);
    			int NewNumber1 = rndNumber.Next(100, 999);
    			int NewNumber2 = rndNumber.Next(100, 999);
    			// Create an item number from the random numbers
    			String strItemNumber = NewNumber1.ToString() + "-" + NewNumber2.ToString();
    
    			// Display the created item number in the Item # text box
    			this.txtItemNumber.Text = strItemNumber;
    		}
    	}
    }
    
  12. Return to the form and double-click the Close button
  13. Implement it as follows:
     
    private void btnClose_Click(object sender, System.EventArgs e)
    {
    	Close();
    }
  14. Save all 

Item Addition

The primary operation performed on a list is to create one. One of the biggest advantages of using a linked list is that you don't have to specify in advance the number of items of the list as done for an array. You can just start adding items. The ArrayList class makes this possible with the Add() method. Its syntax is:

public virtual int Add(object value);

The argument of this method is the value to add to the list. If the method succeeds with the addition, it returns the position where the value was added in the list. This is usually the last position in the list. Here are examples:

private void Form1_Load(object sender, System.EventArgs e)
{
	ArrayList lstNumbers = new ArrayList();
				 
	lstNumbers.Add(452.35);
	lstNumbers.Add(47.58);
	lstNumbers.Add(273.48);
	lstNumbers.Add(9672.037);
	lstNumbers.Add(248.52);
}

If the method fails, the compiler would throw an error. One of the errors that could result from failure of this operation would be based on the fact that either a new item cannot be added to the list because the list is read-only, or the list was already full prior to adding the new item.

As you can create a array list that includes any value of type object, you can also create your own class and use it to create a list based on the ArrayList class. To use your own class, when creating it, make sure it is created as a managed object. Here is an example:

using System;

namespace WindowsApplication28
{
	/// <summary>
	/// Summary description for Employee.
	/// </summary>
	public class Employee
	{
		public string   FullName;
		public string   Department;
		public DateTime DateHired;
		public Double   Salary;

		public Employee()
		{
			//
			// TODO: Add constructor logic here
			//
		}
	}
}

Once you have created a managed class, it can be used like any other. To create a list from it, you can declare its array variable in the class that would use it, such as ArrayList arlEmployees;

As discussed earlier, you can create the list by adding items using the Add() method.

 

 

private void btnAdd_Click(object sender, System.EventArgs e)
{
	if( this.btnAdd.Text.Equals("Add") )
	 {
		 this.txtFullName.Text    = "";
		 this.txtDepartment.Text  = "";
		 this.dtpDateHired.Text  = (DateTime.Now).ToString();
		 this.txtSalary.Text      = "";
		 this.btnAdd.Text = "Update";
		 this.txtFullName.Focus();
	 }
	 else
	 {
		 Employee Empl = new Employee();

		 try {
			 Empl.FullName   = this.txtFullName.Text;
			 Empl.Department = this.txtDepartment.Text;
			 Empl.DateHired  = Convert.ToDateTime(this.dtpDateHired.Text);
			 Empl.Salary     = Double.Parse(this.txtSalary.Text);

			 arlEmployees.Add(Empl);
		 }
		 catch(NotSupportedException)
		 {
			 MessageBox.Show("Error: ", "\nThe item could not be added", MessageBoxButtons.OK);
		 }
		 catch(Exception)
		 {
			 MessageBox.Show("The item could not be added to the list");
		 }

		 this.btnAdd.Text = "Add";
	 }
}

The ArrayList.Add() method is used to add one item at a time to the list. If you have more than one item to add, you can use the ArrayList.AddRange() method. Its syntax is:

public virtual void AddRange(ICollection c);

This method takes as argument a list and adds it to the current list.

The Add() method adds a new item at the end of the list. If you want to insert an item anywhere inside the list, you can call the Insert() method.

 

Practical Learning Practical Learning: Adding Items to an ArrayList List

  1. In the New Item property page, to create an inventory, double-click the Add Item button and implement its Click event as follows:
     
    private void btnAddItem_Click(object sender, System.EventArgs e)
    {
    	// Make sure an item is complete before adding it to the inventory
    	if( this.txtItemNumber.Text.Equals("") )
    	{
    		MessageBox.Show("You must enter an item number to complete the record");
    		this.txtItemNumber.Focus();
    		return;
    	}
    
    	if( this.txtDescription.Text.Equals("") )
    	{
    		MessageBox.Show("You must provide a name for the item in order to create its record");
    		this.txtDescription.Focus();
    		return;
    	}
    
    	if( this.txtUnitPrice.Text.Equals("") )
    	{
    		MessageBox.Show("The price of the item is required before saving it");
    		this.txtUnitPrice.Focus();
    		return;
    	}
    
    	CStoreItem item = new CStoreItem();
    	item.ItemNumber = this.txtItemNumber.Text;
    	item.ItemName   = this.txtDescription.Text;
    	item.Size       = this.txtSize.Text;
    	item.UnitPrice  = decimal.Parse(this.txtUnitPrice.Text);
    	StoreItems.Add(item);
    			
    	DateTime tmeNow = DateTime.Now;
    	int mls = tmeNow.Millisecond;
    	// Generate two random numbers between 100 and 999
    	Random rndNumber = new Random(mls);
    	int NewNumber1 = rndNumber.Next(100, 999);
    	int NewNumber2 = rndNumber.Next(100, 999);
    	// Create an item number from the random numbers
    	String strItemNumber = String.Concat(NewNumber1.ToString(), "-", NewNumber2.ToString());
    
    	// Display the created item number in the Item # text box
    	this.txtItemNumber.Text = strItemNumber;
    	this.txtDescription.Text = "";
    	this.txtSize.Text = "";
    	this.txtUnitPrice.Text = "";
    	this.txtDescription.Focus();
    }
  2. Return to the form and click the Store Inventory tab
  3. In the Properties window, click the Events tab and double-click the SelectedIndexChanged field
  4. Implement its event as follows:
     
    private void tabDeptStore_SelectedIndexChanged(object sender, System.EventArgs e)
    {
    	this.dataGrid1.DataSource = null;
    	this.dataGrid1.DataSource = StoreItems;
    }
  5. Execute the application and try creating a few records (let the computer generate item numbers):
     
    Item Name Size Unit Price
    Women Cashmere Lined Glove 8 115.95
    Men Trendy Jacket Medium 45.85
    Women Stretch Flare Jeans Petite 27.75
    Women Belted Sweater Large 15.95
    Girls Classy Handbag One Size 95.95
    Women Casual Dress Shoes 9.5M 45.95
    Boys Hooded Sweatshirt M (7/8) 15.95
    Girls Velour Dress 10 12.55
    Women Lace Desire Panty Medium 7.15
    Infant Girls Ballerina Dress 12M 22.85
    Men Classic Pinstripe Suit 38 145.95
  6. Then click the Store Inventory tab
     
  7. Close the form and return to your programming environment

The Capacity of a List

After declaring an ArrayList variable, it may be empty. As objects are added to it, the list grows. The list can grow tremendously as you wish. The number of items of the list is managed through the memory it occupies and this memory grows as needed. The number of items that the memory allocated is currently using is represented by the ArrayList.Capacity property. This will usually be the least of your concerns.

If for some reason, you want to intervene and control the number of items that your ArrayList list can contain, you can manipulate the Capacity property. For example, you can assign it a constant to set the maximum value that the list can contain. Once again, you will hardly have any reason to use the Capacity property: the compiler knows what to do with it.

A Fixed Size List

A list is usually meant to grow and shrink as necessary. This also lets the compiler manage the memory occupied by the list. In some cases, you may want a list to have a fixed size. To set this flag, you can call the ArrayList.FixedSize() method. It is overloaded in two versions. One of them has the following syntax:

public static ArrayList FixedSize(ArrayList list);

If you set a fixed size on an ArrayList list, you may not be able to add a new item beyond the limit. In fact, if you attempt to do this, you may receive an error. A safe way is to check whether the list is fixed before performing a related operation. To find out whether a list is fixed, you can check the ArrayList.IsFixedSize property.

The Number of Items in the List

When using a list, at any time, you should be able to know the number of items that the list contains. This information is provided by the ArrayList.Count property. The Capacity and the Count have this in common: the value of each increases as the list grows and the same value decreases if the list shrinks. It is important to know that, although they look alike, there are various differences between the capacity of a list and the number of items it contains. Capacity is a read/write property. This means that, as we saw above, you can assign a value to the capacity to fix the number of items that the list can contain. You can also retrieve the value of the Capacity. The Count is read-only because it is used by the compiler to count the current number of items of the items and this counting is performed without your intervention.

Practical Learning Practical Learning: Counting Items

  1. To get a count of items while the user is adding them to the list, change the Click event of the Add Item button as follows:
     
    System.Void btnAddItem_Click(System.Object   sender, System.EventArgs   e)
    {
    	 . . . No Change
    
    	 StoreItem.CStoreItem item = new StoreItem.CStoreItem;
    	 item.ItemNumber = this.txtItemNumber.Text;
    	 item.ItemName   = this.txtDescription.Text;
    	 item.Size       = this.txtSize.Text;
    	 item.UnitPrice  = this.txtUnitPrice.Text.ToDouble(0);
    	 StoreItems.Add(item);
    			
    this.lblInventoryCount.Text = String.Format("Store Current Inventory: {0} Item", this.StoreItems.Count.ToString()); 
    	 
     	. . . No Change
    }
  2. Execute the application and add a few items to the inventory
     
  3. Close the form and return to your programming environment

A List Arrangement

When using the Add(), the AddRange(), or the Insert() methods to populate an ArrayList object, the item or the group of items is added to the end of the list in a consecutive manner. If you want to reverse this arrangement, you can call the Reverse() method. This method is provided in two versions. One of the versions has the following syntax:

public virtual void Reverse();

This method considers all items of a list and changes their positions in the exact opposite order. The first item becomes the last. The item before last becomes the second in the new list, and so on. If you want to reverse only a range of items in the list, you can use the other version of this method whose syntax is:

public virtual void Reverse(int index, int count);

In some cases, you may want the list to be arranged in an order validated by the language used on the computer. For example, if you create a list of names, you may want to display those names in alphabetical order. If you create a list of employees, you may want to display the list of employees by seniority, based on the date they were hired. The ability to arrange the list in a set order can be handled by the Sort() method. Its syntax is:

public virtual void Sort();

If the items in the list are made of strings, this method would arrange them in alphabetical order. If the items are numeric values, calling this method would arrange the list in incremental order. If the list is made of dates, when this method is called, the compiler would refer to the options set in the Regional Settings of the Control and arrange them accordingly in chronological order.

A Read-Only List

One of the reason for creating a list is to be able to add items to it, edit its items, retrieve an item, or delete items from it. These are the default operations. You can still limit these operations as you judge them unnecessary. For example, you may create a list and then initialize it with the items that you want the list to only have. If you don't intend to have the user adding items to it, you can create the list as read-only. To do this, you can call the ArrayList.ReadOnly() method. It is overloaded with two static versions as follows:

public static ArrayList ReadOnly(ArrayList list);
public static IList ReadOnly(IList list);

These methods are static. This means that you don't need to declare an instance of ArrayList to call them. Instead, to make the list read-only, call the ArrayList.ReadOnly() method and pass your ArrayList variable to it.

Some operations cannot be performed on a read-only list. To perform such operations, you can first find out whether an ArrayList list is read-only. This is done by checking its IsReadOnly property.

Item Retrieval

Once a list is ready, you can perform different types of operations on it. Besides adding items, one of the most regular operations performed on a list consists of locating and retrieving an item. You have various options. To retrieve a single item based on its position, you can use the Item property which accesses each item using square brackets. Like a normal array, an ArrayList list is zero-based. Another issue to keep in mind is that the ArrayList.Item[] property produces an Object value. Therefore, you may have to cast this value to your type of value to get it right. Here are examples of using this property:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace GCS
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.TextBox txtFullName;
		private System.Windows.Forms.TextBox txtDepartment;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.DateTimePicker dtpDateHired;
		private System.Windows.Forms.TextBox txtSalary;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.Button btnAdd;
		private System.Windows.Forms.Button btnFirst;
		private System.Windows.Forms.Button btnPrevious;
		private System.Windows.Forms.Button btnLast;
		private System.Windows.Forms.Button btnNext;
		private System.Windows.Forms.Button btnClose;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;
		ArrayList arlEmployees;
		int CurrentPosition;

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
			this.label1 = new System.Windows.Forms.Label();
			this.txtFullName = new System.Windows.Forms.TextBox();
			this.txtDepartment = new System.Windows.Forms.TextBox();
			this.label2 = new System.Windows.Forms.Label();
			this.label3 = new System.Windows.Forms.Label();
			this.dtpDateHired = new System.Windows.Forms.DateTimePicker();
			this.txtSalary = new System.Windows.Forms.TextBox();
			this.label4 = new System.Windows.Forms.Label();
			this.btnAdd = new System.Windows.Forms.Button();
			this.btnFirst = new System.Windows.Forms.Button();
			this.btnPrevious = new System.Windows.Forms.Button();
			this.btnLast = new System.Windows.Forms.Button();
			this.btnNext = new System.Windows.Forms.Button();
			this.btnClose = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(16, 18);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(72, 16);
			this.label1.TabIndex = 0;
			this.label1.Text = "Full Name:";
			// 
			// txtFullName
			// 
			this.txtFullName.Location = new System.Drawing.Point(104, 16);
			this.txtFullName.Name = "txtFullName";
			this.txtFullName.Size = new System.Drawing.Size(168, 20);
			this.txtFullName.TabIndex = 1;
			this.txtFullName.Text = "";
			// 
			// txtDepartment
			// 
			this.txtDepartment.Location = new System.Drawing.Point(104, 48);
			this.txtDepartment.Name = "txtDepartment";
			this.txtDepartment.Size = new System.Drawing.Size(168, 20);
			this.txtDepartment.TabIndex = 3;
			this.txtDepartment.Text = "";
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(16, 48);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(72, 16);
			this.label2.TabIndex = 2;
			this.label2.Text = "Department:";
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(16, 80);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(72, 16);
			this.label3.TabIndex = 4;
			this.label3.Text = "Date Hired:";
			// 
			// dtpDateHired
			// 
			this.dtpDateHired.CustomFormat = "dddd dd MMM yyyy";
			this.dtpDateHired.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
			this.dtpDateHired.Location = new System.Drawing.Point(104, 80);
			this.dtpDateHired.Name = "dtpDateHired";
			this.dtpDateHired.Size = new System.Drawing.Size(168, 20);
			this.dtpDateHired.TabIndex = 5;
			// 
			// txtSalary
			// 
			this.txtSalary.Location = new System.Drawing.Point(104, 112);
			this.txtSalary.Name = "txtSalary";
			this.txtSalary.Size = new System.Drawing.Size(168, 20);
			this.txtSalary.TabIndex = 7;
			this.txtSalary.Text = "";
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(16, 112);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(72, 16);
			this.label4.TabIndex = 6;
			this.label4.Text = "Salary:";
			// 
			// btnAdd
			// 
			this.btnAdd.Location = new System.Drawing.Point(24, 144);
			this.btnAdd.Name = "btnAdd";
			this.btnAdd.Size = new System.Drawing.Size(72, 23);
			this.btnAdd.TabIndex = 8;
			this.btnAdd.Text = "Add";
			this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
			// 
			// btnFirst
			// 
			this.btnFirst.Location = new System.Drawing.Point(104, 144);
			this.btnFirst.Name = "btnFirst";
			this.btnFirst.Size = new System.Drawing.Size(40, 23);
			this.btnFirst.TabIndex = 9;
			this.btnFirst.Text = "| <";
			this.btnFirst.Click += new System.EventHandler(this.btnFirst_Click);
			// 
			// btnPrevious
			// 
			this.btnPrevious.Location = new System.Drawing.Point(144, 144);
			this.btnPrevious.Name = "btnPreviou";
			this.btnPrevious.Size = new System.Drawing.Size(40, 23);
			this.btnPrevious.TabIndex = 10;
			this.btnPrevious.Text = "<<";
			this.btnPrevious.Click += new System.EventHandler(this.btnPrevious_Click);
			// 
			// btnLast
			// 
			this.btnLast.Location = new System.Drawing.Point(232, 144);
			this.btnLast.Name = "btnLast";
			this.btnLast.Size = new System.Drawing.Size(40, 23);
			this.btnLast.TabIndex = 12;
			this.btnLast.Text = "> |";
			this.btnLast.Click += new System.EventHandler(this.btnLast_Click);
			// 
			// btnNext
			// 
			this.btnNext.Location = new System.Drawing.Point(192, 144);
			this.btnNext.Name = "btnNext";
			this.btnNext.Size = new System.Drawing.Size(40, 23);
			this.btnNext.TabIndex = 11;
			this.btnNext.Text = ">>";
			this.btnNext.Click += new System.EventHandler(this.btnNext_Click);
			// 
			// btnClose
			// 
			this.btnClose.Location = new System.Drawing.Point(280, 144);
			this.btnClose.Name = "btnClose";
			this.btnClose.Size = new System.Drawing.Size(72, 23);
			this.btnClose.TabIndex = 13;
			this.btnClose.Text = "Close";
			this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(368, 182);
			this.Controls.Add(this.btnClose);
			this.Controls.Add(this.btnLast);
			this.Controls.Add(this.btnNext);
			this.Controls.Add(this.btnPrevious);
			this.Controls.Add(this.btnFirst);
			this.Controls.Add(this.btnAdd);
			this.Controls.Add(this.txtSalary);
			this.Controls.Add(this.label4);
			this.Controls.Add(this.dtpDateHired);
			this.Controls.Add(this.label3);
			this.Controls.Add(this.txtDepartment);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.txtFullName);
			this.Controls.Add(this.label1);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.MaximizeBox = false;
			this.Name = "Form1";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Employees Record";
			this.Load += new System.EventHandler(this.Form1_Load);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}

		private void Form1_Load(object sender, System.EventArgs e)
		{
			arlEmployees = new ArrayList();
		}

		private void btnAdd_Click(object sender, System.EventArgs e)
		{
			if( this.btnAdd.Text.Equals("Add") )
	 {
		 this.txtFullName.Text    = "";
		 this.txtDepartment.Text  = "";
		 this.dtpDateHired.Text  = (DateTime.Now).ToString();
		 this.txtSalary.Text      = "";
		 this.btnAdd.Text = "Update";
		 this.txtFullName.Focus();
	 }
	 else
	 {
		 Employee Empl = new Employee();

		 try {
			 Empl.FullName   = this.txtFullName.Text;
			 Empl.Department = this.txtDepartment.Text;
			 Empl.DateHired  = Convert.ToDateTime(this.dtpDateHired.Text);
			 Empl.Salary     = Double.Parse(this.txtSalary.Text);

			 arlEmployees.Add(Empl);
		 }
		 catch(NotSupportedException)
		 {
			 MessageBox.Show("The item could not be added");
		 }
		 catch(Exception)
		 {
			 MessageBox.Show("The item could not be added to the list");
		 }
				this.txtFullName.Text    = "";
				this.txtDepartment.Text  = "";
				this.dtpDateHired.Text  = (DateTime.Now).ToString();
				this.txtSalary.Text      = "";
		 this.btnAdd.Text = "Add";
				this.txtFullName.Focus();
	 }
		}

		private void btnFirst_Click(object sender, System.EventArgs e)
		{
			CurrentPosition = 0;
	 Employee Empl = new Employee();

	 try {
		 Empl = (Employee)arlEmployees[CurrentPosition];

		 this.txtFullName.Text   = Empl.FullName;
		 this.txtDepartment.Text = Empl.Department;
		 this.dtpDateHired.Text  = Empl.DateHired.ToString();
		 this.txtSalary.Text     = Empl.Salary.ToString();
	 }
	 catch(ArgumentOutOfRangeException)
	 {
		 MessageBox.Show("The item could not be retrieved");
	 }
	 catch(Exception)
	 {
		 MessageBox.Show("There was a problem retrieving the item");
	 }
		}

		private void btnPrevious_Click(object sender, System.EventArgs e)
		{
			Employee Empl = new Employee();

	 if( CurrentPosition == 0 )
		 return;
	 else
	 {
		 CurrentPosition = CurrentPosition - 1;

		 try {
			 Empl = (Employee)arlEmployees[CurrentPosition];

			 this.txtFullName.Text   = Empl.FullName;
			 this.txtDepartment.Text = Empl.Department;
			 this.dtpDateHired.Text  = Empl.DateHired.ToString();
			 this.txtSalary.Text     = Empl.Salary.ToString();
		 }
		 catch(ArgumentOutOfRangeException)
		 {
			 MessageBox.Show("The item could not be retrieved");
		 }
		 catch(Exception)
		 {
			 MessageBox.Show("There was a problem retrieving the item");
		 }
	 }
		}

		private void btnNext_Click(object sender, System.EventArgs e)
		{
			Employee Empl = new Employee();

	 if( CurrentPosition == (arlEmployees.Count - 1) )
		 return;
	 else
	 {
		 CurrentPosition = CurrentPosition + 1;
				 
		 try {
			 Empl = (Employee)arlEmployees[CurrentPosition];

			 this.txtFullName.Text   = Empl.FullName;
			 this.txtDepartment.Text = Empl.Department;
			 this.dtpDateHired.Text  = Empl.DateHired.ToString();
			 this.txtSalary.Text     = Empl.Salary.ToString();
		 }
		 catch(ArgumentOutOfRangeException AOOR)
		 {
			 MessageBox.Show("The item could not be retrieved");
		 }
		 catch(Exception)
		 {
			 MessageBox.Show("There was a problem retrieving the item");
		 }
	 }
		}

		private void btnLast_Click(object sender, System.EventArgs e)
		{
			CurrentPosition = arlEmployees.Count - 1;					  
            Employee Empl = new Employee();

	try {
		Empl = (Employee)arlEmployees[CurrentPosition];

		  this.txtFullName.Text   = Empl.FullName;
		  this.txtDepartment.Text = Empl.Department;
		  this.dtpDateHired.Text  = Empl.DateHired.ToString();
		  this.txtSalary.Text     = Empl.Salary.ToString();
	 }
	 catch(ArgumentOutOfRangeException)
	 {
		  MessageBox.Show("The item could not be retrieved");
	 }
	 catch(Exception)
	 {
		  MessageBox.Show("There was a problem retrieving the item");
	 }
		}

		private void btnClose_Click(object sender, System.EventArgs e)
		{
			Close();
		}
	}
}

Item Location

Instead of the square brackets that allow you to retrieve an item based on its position, you can look for an item based on its complete definition. You have various options. You can first "build" an item and ask the compiler to check whether any item in the list matches your definition. To perform this search, you can call the ArrayList.Contains() method. Its syntax is:

public virtual bool Contains(object item);

The item to look for is passed as argument to the method. The compiler would look for exactly the item, using its definition, in the list. If any detail of the argument fails to match any item of the ArrayList list, the method would return false. If all characteristics of the argument correspond to an item of the list, the method returns true.

Another option to look for an item in a list consists of calling the ArrayList.BinarySearch() method. It is overloaded in three versions and one of them uses the following syntax:

public virtual int BinarySearch(object value);

The item to look for is passed argument to the method.

 

Item Deletion

As opposed to adding an item to a list, you may want to remove one. To perform this operation, you have various options. You can ask the compiler to look for an item in the list and if, or once, the compile finds it, it would delete the item. To perform this type of deletion, you can call the ArrayList.Remove() method. Its syntax is:

public virtual void Remove(object obj);

This method accepts as argument the item that you want to delete from the list. To perform this operation, the list must not be read-only.

The Remove() method allows you to specify the exact item you want to delete from a list. Another option you have consists of deleting an item based on its position. This is done using the RemoveAt() method whose syntax is:

public virtual void RemoveAt(int index);

With this method, the position of the item is passed as argument. If the position is not valid because either it is lower or higher than the current Count, the compiler would throw an ArgumentOutOfRangeException exception.

To remove all items from a list at once, you can call the ArrayList.Clear() method. Its syntax is:

public virtual void Clear();

 

 

Home Copyright © 2004-2010 FunctionX, Inc.