|
Dictionary-Based Collections |
|
Introduction to Dictionaries |
|
Description |
A dictionary is a list of items with the following two rules:
In some cases, in addition to these two rules, the items should - in some cases must - be ordered. To order the items, the keys are used. Because in most cases a dictionary is made of words, the keys are ordered in alphabetical order. A dictionary can also be made of items whose keys are date values. In this case, the items would be ordered in chronological order.
There are various types of dictionary types of list used in daily life. The word "dictionary" here does not imply the traditional dictionary that holds the words and their meanings in the English language. The concept is applied in various scenarios.
| (Name) | Text | TextAlign | Width |
| colCategory | Category | 90 | |
| colDaily | Daily | Right | |
| colWeekly | Weekly | Right | |
| colMonthly | Monthly | Right | |
| colWeekend | Weekend | Right |
| ListViewItem | SubItems | SubItems | SubItems | SubItems |
| Text | Text | Text | Text | |
| Economy | 35.95 | 32.75 | 28.95 | 24.95 |
| Compact | 39.95 | 35.75 | 32.95 | 28.95 |
| Standard | 45.95 | 39.75 | 35.95 | 32.95 |
| Full Size | 49.95 | 42.75 | 38.95 | 35.95 |
| Mini Van | 55.95 | 50.75 | 45.95 | 42.95 |
| SUV | 55.95 | 50.75 | 45.95 | 42.95 |
| Truck | 42.75 | 38.75 | 35.95 | 32.95 |
| Van | 69.95 | 62.75 | 55.95 | 52.95 |

| (Name) | Text | TextAlign | Width |
| colEmployeeNumber | Empl # | 45 | |
| colFirstName | First Name | 65 | |
| colLastName | Last Name | 65 | |
| colFullName | Full Name | 140 | |
| colTitle | Title | 120 | |
| colHourlySalary | Hourly Salary | Right | 75 |
![]() |
||||||||||||||||
|
![]() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
// This code is used to create and display the customer's full name
private void txtLastName_Leave(object sender, EventArgs e)
{
string strFirstName = txtFirstName.Text;
string strLastName = txtLastName.Text;
string strFullName;
if (strFirstName.Length == 0)
strFullName = strLastName;
else
strFullName = strLastName + ", " + strFirstName;
txtFullName.Text = strFullName;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BethesdaCarRental1
{
[Serializable]
public class Employee
{
public string FirstName;
public string LastName;
public string Title;
public double HourlySalary;
public string FullName
{
get { return LastName + ", " + FirstName; }
}
// This default constructor says that
// the employee is not defined
public Employee()
{
FirstName = "Unknown";
LastName = "Unknown";
Title = "N/A";
HourlySalary = 0.00;
}
// This constructor completely defines an employee
public Employee(string fname, string lname,
string title, double salary)
{
FirstName = fname;
LastName = lname;
Title = title;
HourlySalary = salary;
}
}
}
|
| (Name) | Text | Width |
| colDrvLicNbr | Driver's Lic. # | 100 |
| colFullName | Full Name | 100 |
| colAddress | Address | 160 |
| colCity | City | 100 |
| colState | State | 38 |
| colZIPCode | ZIPCode |
![]() |
||||||||||||||||
|
![]() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BethesdaCarRental1
{
[Serializable]
public class Customer
{
public string FullName;
public string Address;
public string City;
public string State;
public string ZIPCode;
public Customer()
{
FullName = "";
Address = "";
City = "";
State = "";
ZIPCode = "";
}
// This constructor defines a customer
public Customer(string fName,
string adr, string ct,
string ste, string zip)
{
FullName = fName;
Address = adr;
City = ct;
State = ste;
ZIPCode = zip;
}
}
}
|
![]() |
![]() |
| BMW: 335i | Chevrolet Avalanche |
![]() |
![]() |
| Honda Accord | Mazda Miata |
![]() |
![]() |
| Chevrolet Aveo | Ford E150XL |
![]() |
![]() |
| Buick Lacrosse | Honda Civic |
![]() |
![]() |
| Ford F-150 | Mazda Mazda5 |
![]() |
![]() |
| Volvo S40 | Land Rover LR3 |
![]() |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
private void btnSelectPicture_Click(object sender, EventArgs e)
{
if (dlgPicture.ShowDialog() == DialogResult.OK)
{
lblPictureName.Text = dlgPicture.FileName;
pbxCar.Image = Image.FromFile(lblPictureName.Text);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BethesdaCarRental1
{
[Serializable]
public class Car
{
public string Make;
public string Model;
public int Year;
public string Category;
public bool HasCDPlayer;
public bool HasDVDPlayer;
public bool IsAvailable;
public Car()
{
Make = "";
Model = "";
Year = 0;
Category = "";
HasCDPlayer = false;
HasDVDPlayer = false;
IsAvailable = false;
}
public Car(string mk, string mdl,
int yr, string cat, bool cd,
bool dvd, bool avl)
{
Make = mk;
Model = mdl;
Year = yr;
Category = cat;
HasCDPlayer = cd;
HasDVDPlayer = dvd;
IsAvailable = avl;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BethesdaCarRental1
{
[Serializable]
public class RentalOrder
{
public string EmployeeNumber;
// The following flag will allow us to update/know whether
// * The car is currently being used by the customer.
// That is, if the car has been picked up by the customer
// * The customer has brought the car back
public string OrderStatus;
// Because every car has a tag number
// and that tag number will not change
// during the lifetime of a car (while the car remains with our
// car rental company, we will
// use only the tag number here.
// The other pieces of information will
// be retrieved from the list of cars
public string CarTagNumber;
// We will identify the customer by the number
// and the name on his or her driver's license
public string CustomerDrvLicNbr;
public string CustomerName;
// Although he or she may keep the same driver's
// license number for a lifetime, a customer who
// rents cars at different times with this company
// over months or years may have different addresses.
// Therefore, although we will primarily retrieve the
// customer's address from the list of customers,
// we will give the clerk the ability to change this
// information on a rental order. This means that the
// same customer could have different information on
// different rental orders.
// For this reason, each rental order will its own set
// of these pieces of information
public string CustomerAddress;
public string CustomerCity;
public string CustomerState;
public string CustomerZIPCode;
public string CarCondition;
public string TankLevel;
// This information will be entered when the car is being rented
public int MileageStart;
// This information will be entered when the car is brought back
public int MileageEnd;
// This information will be entered when the car is being rented
public DateTime DateStart;
// This information will be entered when the car is brought back
public DateTime DateEnd;
public int Days;
// This information will be entered when the car is being rented
public double RateApplied;
// This calculation should occur when the car is brought back
public double SubTotal;
public double TaxRate;
public double TaxAmount;
public double OrderTotal;
public RentalOrder()
{
}
}
}
|
![]() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
private void dtpStartDate_ValueChanged(object sender, EventArgs e)
{
dtpEndDate.Value = dtpStartDate.Value;
}
|
// This event approximately evaluates the number of days as a
// difference between the end date and the starting date
private void dtpEndDate_ValueChanged(object sender, EventArgs e)
{
int days;
DateTime dteStart = this.dtpStartDate.Value;
DateTime dteEnd = this.dtpEndDate.Value;
// Let's calculate the difference in days
TimeSpan tme = dteEnd - dteStart;
days = tme.Days;
// If the customer returns the car the same day,
// we consider that the car was rented for 1 day
if (days == 0)
days = 1;
txtDays.Text = days.ToString();
// At any case, we will let the clerk specify the actual number of days
}
|
private void btnRentalRates_Click(object sender, EventArgs e)
{
RentalRates wndRates = new RentalRates();
wndRates.Show();
}
|
private void btnCalculate_Click(object sender, EventArgs e)
{
int Days = 0;
double RateApplied = 0.00;
double SubTotal = 0.00;
double TaxRate = 0.00;
double TaxAmount = 0.00;
double OrderTotal = 0.00;
try
{
Days = int.Parse(this.txtDays.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Number of Days");
}
try
{
RateApplied = double.Parse(txtRateApplied.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Amount for Rate Applied");
}
SubTotal = Days * RateApplied;
txtSubTotal.Text = SubTotal.ToString("F");
try
{
TaxRate = double.Parse(txtTaxRate.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid Tax Rate");
}
TaxAmount = SubTotal * TaxRate / 100;
txtTaxAmount.Text = TaxAmount.ToString("F");
OrderTotal = SubTotal + TaxAmount;
txtOrderTotal.Text = OrderTotal.ToString("F");
}
|
private void docPrint_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawLine(new Pen(Color.Black, 2), 80, 90, 750, 90);
e.Graphics.DrawLine(new Pen(Color.Black, 1), 80, 93, 750, 93);
string strDisplay = "Bethesda Car Rental";
System.Drawing.Font fntString = new Font("Times New Roman", 28,
FontStyle.Bold);
e.Graphics.DrawString(strDisplay, fntString,
Brushes.Black, 240, 100);
strDisplay = "Car Rental Order";
fntString = new System.Drawing.Font("Times New Roman", 22,
FontStyle.Regular);
e.Graphics.DrawString(strDisplay, fntString,
Brushes.Black, 320, 150);
e.Graphics.DrawLine(new Pen(Color.Black, 1), 80, 187, 750, 187);
e.Graphics.DrawLine(new Pen(Color.Black, 2), 80, 190, 750, 190);
fntString = new System.Drawing.Font("Times New Roman", 12,
FontStyle.Bold);
e.Graphics.DrawString("Receipt #: ", fntString,
Brushes.Black, 100, 220);
fntString = new System.Drawing.Font("Times New Roman", 12,
FontStyle.Regular);
e.Graphics.DrawString(txtReceiptNumber.Text, fntString,
Brushes.Black, 260, 220);
e.Graphics.DrawLine(new Pen(Color.Black, 1), 100, 240, 380, 240);
fntString = new System.Drawing.Font("Times New Roman", 12,
FontStyle.Bold);
e.Graphics.DrawString("Processed By: ", fntString,
Brushes.Black, 420, 220);
fntString = new System.Drawing.Font("Times New Roman", 12,
FontStyle.Regular);
e.Graphics.DrawString(txtEmployeeName.Text, fntString,
Brushes.Black, 550, 220);
e.Graphics.DrawLine(new Pen(Color.Black, 1), 420, 240, 720, 240);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.FillRectangle(Brushes.Gray,
new Rectangle(100, 260, 620, 20));
e.Graphics.DrawRectangle(Pens.Black,
new Rectangle(100, 260, 620, 20));
e.Graphics.DrawString("Customer", fntString,
Brushes.White, 100, 260);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Driver's License #: ", fntString,
Brushes.Black, 100, 300);
e.Graphics.DrawString("Name: ", fntString,
Brushes.Black, 420, 300);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(txtDrvLicNumber.Text, fntString,
Brushes.Black, 260, 300);
e.Graphics.DrawString(txtCustomerName.Text, fntString,
Brushes.Black, 540, 300);
e.Graphics.DrawLine(new Pen(Color.Black, 1), 100, 320, 720, 320);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Address: ", fntString,
Brushes.Black, 100, 330);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(txtCustomerAddress.Text, fntString,
Brushes.Black, 260, 330);
e.Graphics.DrawLine(new Pen(Color.Black, 1), 100, 350, 720, 350);
strDisplay = txtCustomerCity.Text + " " +
cbxCustomerStates.Text + " " +
txtCustomerZIPCode.Text;
fntString = new System.Drawing.Font("Times New Roman",
12, FontStyle.Regular);
e.Graphics.DrawString(strDisplay, fntString,
Brushes.Black, 260, 360);
e.Graphics.DrawLine(new Pen(Color.Black, 1), 260, 380, 720, 380);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.FillRectangle(Brushes.Gray,
new Rectangle(100, 410, 620, 20));
e.Graphics.DrawRectangle(Pens.Black,
new Rectangle(100, 410, 620, 20));
e.Graphics.DrawString("Car Information", fntString,
Brushes.White, 100, 410);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Tag #: ", fntString,
Brushes.Black, 100, 450);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(txtTagNumber.Text, fntString,
Brushes.Black, 260, 450);
e.Graphics.DrawLine(new Pen(Color.Black, 1), 100, 470, 380, 470);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Year: ", fntString,
Brushes.Black, 420, 450);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(txtCarYear.Text, fntString,
Brushes.Black, 530, 450);
e.Graphics.DrawLine(new Pen(Color.Black, 1), 420, 470, 720, 470);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Make: ", fntString,
Brushes.Black, 100, 480);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(txtMake.Text, fntString,
Brushes.Black, 260, 480);
e.Graphics.DrawLine(new Pen(Color.Black, 1), 100, 500, 380, 500);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Model: ", fntString,
Brushes.Black, 420, 480);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(txtModel.Text, fntString,
Brushes.Black, 530, 480);
e.Graphics.DrawLine(new Pen(Color.Black, 1), 420, 500, 720, 500);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Car Condition: ", fntString,
Brushes.Black, 100, 510);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(cbxCarConditions.Text, fntString,
Brushes.Black, 260, 510);
e.Graphics.DrawLine(new Pen(Color.Black, 1), 100, 530, 380, 530);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Tank Level: ", fntString,
Brushes.Black, 420, 510);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(cbxTankLevels.Text, fntString,
Brushes.Black, 530, 510);
e.Graphics.DrawLine(new Pen(Color.Black, 1), 420, 530, 720, 530);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Mileage Start:", fntString,
Brushes.Black, 100, 540);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(txtMileageStart.Text, fntString,
Brushes.Black, 260, 540);
e.Graphics.DrawLine(new Pen(Color.Black, 1),
100, 560, 380, 560);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Mileage End:", fntString,
Brushes.Black, 420, 540);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(txtMileageEnd.Text, fntString,
Brushes.Black, 530, 540);
e.Graphics.DrawLine(new Pen(Color.Black, 1),
420, 560, 720, 560);
e.Graphics.FillRectangle(Brushes.Gray,
new Rectangle(100, 590, 620, 20));
e.Graphics.DrawRectangle(Pens.Black,
new Rectangle(100, 590, 620, 20));
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Order Timing Information", fntString,
Brushes.White, 100, 590);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Start Date:", fntString,
Brushes.Black, 100, 620);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(dtpStartDate.Value.ToString("D"),
fntString, Brushes.Black, 260, 620);
e.Graphics.DrawLine(new Pen(Color.Black, 1),
100, 640, 720, 640);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("End Date:", fntString,
Brushes.Black, 100, 650);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(dtpEndDate.Value.ToString("D"), fntString,
Brushes.Black, 260, 650);
e.Graphics.DrawLine(new Pen(Color.Black, 1),
100, 670, 520, 670);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Days:", fntString,
Brushes.Black, 550, 650);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(txtDays.Text, fntString,
Brushes.Black, 640, 650);
e.Graphics.DrawLine(new Pen(Color.Black, 1),
550, 670, 720, 670);
e.Graphics.FillRectangle(Brushes.Gray,
new Rectangle(100, 700, 620, 20));
e.Graphics.DrawRectangle(Pens.Black,
new Rectangle(100, 700, 620, 20));
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Order Evaluation", fntString,
Brushes.White, 100, 700);
StringFormat fmtString = new StringFormat();
fmtString.Alignment = StringAlignment.Far;
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Rate Applied:", fntString,
Brushes.Black, 100, 740);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(txtRateApplied.Text, fntString,
Brushes.Black, 300, 740, fmtString);
e.Graphics.DrawLine(new Pen(Color.Black, 1),
100, 760, 380, 760);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Tax Rate:", fntString,
Brushes.Black, 420, 740);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(txtTaxRate.Text, fntString,
Brushes.Black, 640, 740, fmtString);
e.Graphics.DrawString("%", fntString,
Brushes.Black, 640, 740);
e.Graphics.DrawLine(new Pen(Color.Black, 1),
420, 760, 720, 760);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Sub-Total:", fntString,
Brushes.Black, 100, 770);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(txtSubTotal.Text, fntString,
Brushes.Black, 300, 770, fmtString);
e.Graphics.DrawLine(new Pen(Color.Black, 1),
100, 790, 380, 790);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Tax Amount:", fntString,
Brushes.Black, 420, 770);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(txtTaxAmount.Text, fntString,
Brushes.Black, 640, 770, fmtString);
e.Graphics.DrawLine(new Pen(Color.Black, 1),
420, 790, 720, 790);
fntString = new Font("Times New Roman", 12, FontStyle.Bold);
e.Graphics.DrawString("Order Total:", fntString,
Brushes.Black, 420, 800);
fntString = new Font("Times New Roman", 12, FontStyle.Regular);
e.Graphics.DrawString(txtOrderTotal.Text, fntString,
Brushes.Black, 640, 800, fmtString);
e.Graphics.DrawLine(new Pen(Color.Black, 1),
420, 820, 720, 820);
}
|
private void btnPrint_Click(object sender, EventArgs e)
{
if (dlgPrint.ShowDialog() == DialogResult.OK)
docPrint.Print();
}
|
private void btnPrintPreview_Click(object sender, EventArgs e)
{
dlgPrintPreview.ShowDialog();
}
|
![]() |
||||||||||||||||||
|
private void btnRentalOrders_Click(object sender, EventArgs e)
{
OrderProcessing dlgOrder = new OrderProcessing();
dlgOrder.ShowDialog();
}
|
private void btnCars_Click(object sender, EventArgs e)
{
CarEditor dlgCars = new CarEditor();
dlgCars.ShowDialog();
}
|
private void btnEmployees_Click(object sender, EventArgs e)
{
Employees dlgEmployees = new Employees();
dlgEmployees.ShowDialog();
}
|
private void btnCustomers_Click(object sender, EventArgs e)
{
Customers dlgCustomers = new Customers();
dlgCustomers.ShowDialog();
}
|
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
|
|
Creating a Dictionary-Based Collection Class |
To support dictionary-based lists, the .NET Framework provides various interfaces and classes. The interfaces allow you to create your own dictionary type of collection class. The classes allow you to directly create a dictionary-based list with an already built-in functionality. The NET Framework provides support for dictionary-based collections through two classes: Hashtable and SortedList. Both classes implement:
The Hashtable class implements the ISerializable interface, which makes it possible for the list to be serialized. Still, the SortedList class is marked with the Serializable attribute, which makes it possible to file process its list.
The .NET Framework also provides dictionary-types through generic classes. From the System.Collections.Generic namespace, to create a dictionary type of collection, you can use either the Dictionary, the SortedDictionary, or the SortedList class. The System.Collections.Generic.Dictionary class is equivalent to the System.Collections.Hashtable class. The System.Collections.Generic.SortedList class is equivalent to the System.Collections.SortedList class. The System.Collections.Generic.SortedDictionary class is equivalent to the System.Collections.Generic.SortedList class with some differences in the way both classes deal with memory management.
If you decide to use either the System.Collections.Generic.Dictionary or the System.Collections.Generic.SortedList class, when declaring the variable, you must remember to specify the name of the class whose collection is being created.
Before using a dictionary-type of list, you can declare a variable using one of the constructors of the class. Here is an example:
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
public class Exercise : Form
{
public Exercise()
{
InitializeComponent();
}
void InitializeComponent()
{
Text = "Students";
Load += new EventHandler(StartForm);
}
void StartForm(object sender, EventArgs e)
{
Hashtable Students = new Hashtable();
}
}
public class Program
{
static int Main()
{
System.Windows.Forms.Application.Run(new Exercise());
return 0;
}
}
In this case, the primary list would be empty.
|
|
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;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace BethesdaCarRental1a
{
public partial class CarEditor : Form
{
Dictionary<string, Car> lstCars;
public CarEditor()
{
InitializeComponent();
}
private void btnSelectPicture_Click(object sender, EventArgs e)
{
if (dlgPicture.ShowDialog() == DialogResult.OK)
{
lblPictureName.Text = dlgPicture.FileName;
pbxCar.Image = Image.FromFile(lblPictureName.Text);
}
}
private void CarEditor_Load(object sender, EventArgs e)
{
Car vehicle = new Car();
BinaryFormatter bfmCars = new BinaryFormatter();
// This is the file that holds the list of items
string FileName = @"C:\Bethesda Car Rental\Cars.crs";
lblPictureName.Text = ".";
if (File.Exists(FileName))
{
FileStream stmCars = new FileStream(FileName,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
try
{
// Retrieve the list of cars
lstCars =
(Dictionary<string, Car>)bfmCars.Deserialize(stmCars);
}
finally
{
stmCars.Close();
}
}
else
lstCars = new Dictionary<string, Car>();
}
}
}
|
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;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace BethesdaCarRental1a
{
public partial class RentalOrders : Form
{
int ReceiptNumber;
SortedList<int, RentalOrder> lstRentalOrders;
public RentalOrders()
{
InitializeComponent();
}
. . . No Change
}
}
|
|
Adding Items to the Collection |
To add an item to the list, you can call the Add() method. The syntax of the System.Collections.Hashtable.Add() and the System.Collections.SortedList.Add() methods is:
public virtual void Add(object Key, object Value);
The syntax of the System.Collections.Generic.Dictionary.Add(), the System.Collections.Generic.SortedDictionary.Add(), and the System.Collections.Generic.SortedList.Add() method is:
public void Add(TKey key, TValue value);
As you can see, you must provide the key and the value as the first and second arguments to the method respectively. Here are examples of calling the Add() method:
void StartForm(object sender, EventArgs e)
{
Hashtable Students = new Hashtable();
Students.Add("Hermine", "Tolston");
Students.Add("Patrick", "Donley");
}
When calling the Add() method, you must provide a valid Key argument: it cannot be null. For example, the following code would produce an error:
void StartForm(object sender, EventArgs e)
{
Hashtable Students = new Hashtable();
Students.Add("Hermine", "Tolston");
Students.Add("Patrick", "Donley");
Students.Add(null, "Hannovers");
}
This would produce:

When adding the items to the list, as mentioned in our introduction, each key must be unique: you cannot have two exact keys. If you try adding a key that exists already in the list, the compiler would throw an ArgumentException exception. Based on this, the following code would not work because, on the third call, a "Patrick" key exists already:
void StartForm(object sender, EventArgs e)
{
Hashtable Students = new Hashtable();
Students.Add("Hermine", "Tolston");
Students.Add("Patrick", "Donley");
Students.Add("Chrissie", "Hannovers");
Students.Add("Patrick", "Herzog");
}
This would produce:

This means that, when creating a dictionary type of list, you must define a scheme that would make sure that each key is unique among the other keys in the list.
Besides the Add() method, you can use the indexed property to add an item to the collection. To do this, enter the Key in the square brackets of the property and assign it the desired Value. Here is an example:
void StartForm(object sender, EventArgs e)
{
Hashtable Students = new Hashtable();
Students.Add("Hermine", "Tolston");
Students.Add("Patrick", "Donley");
Students.Add("Chrissie", "Hannovers");
Students.Add("Patricia", "Herzog");
Students["Michael"] = "Herlander";
}
|
|
private void btnSubmit_Click(object sender, EventArgs e)
{
Car vehicle = new Car();
FileStream stmCars = null;
BinaryFormatter bfmCars = new BinaryFormatter();
Directory.CreateDirectory(@"C:\Bethesda Car Rental");
string strFilename = @"C:\Bethesda Car Rental\Cars.crs";
if (txtTagNumber.Text.Length == 0)
{
MessageBox.Show("You must enter the car's tag number");
return;
}
if (txtMake.Text.Length == 0)
{
MessageBox.Show("You must specify the car's manufacturer");
return;
}
if (txtModel.Text.Length == 0)
{
MessageBox.Show("You must enter the model of the car");
return;
}
if (txtYear.Text.Length == 0)
{
MessageBox.Show("You must enter the year of the car");
return;
}
// Create a car
vehicle.Make = txtMake.Text;
vehicle.Model = txtModel.Text;
vehicle.Year = int.Parse(txtYear.Text);
vehicle.Category = cbxCategories.Text;
vehicle.HasCDPlayer = chkCDPlayer.Checked;
vehicle.HasDVDPlayer = chkDVDPlayer.Checked;
vehicle.IsAvailable = chkAvailable.Checked;
// Call the Add method of our collection class to add the car
lstCars.Add(txtTagNumber.Text, vehicle);
// Save the list
stmCars = new FileStream(strFilename,
FileMode.Create,
FileAccess.Write,
FileShare.Write);
try
{
bfmCars.Serialize(stmCars, lstCars);
if (lblPictureName.Text.Length != 0)
{
FileInfo flePicture = new FileInfo(lblPictureName.Text);
flePicture.CopyTo(@"C:\Bethesda Car Rental\" +
txtTagNumber.Text +
flePicture.Extension);
}
txtTagNumber.Text = "";
txtMake.Text = "";
txtModel.Text = "";
txtYear.Text = "";
cbxCategories.Text = "Economy";
chkCDPlayer.Checked = false;
chkDVDPlayer.Checked = false;
chkAvailable.Checked = false;
lblPictureName.Text = ".";
pbxCar.Image = null;
}
finally
{
stmCars.Close();
}
}
|
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;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace BethesdaCarRental1a
{
public partial class Customers : Form
{
Dictionary<string, Customer> lstCustomers;
public Customers()
{
InitializeComponent();
}
internal void ShowCustomers()
{
}
private void Customers_Load(object sender, EventArgs e)
{
lstCustomers = new Dictionary<string, Customer>();
BinaryFormatter bfmCustomers = new BinaryFormatter();
// This is the file that holds the list of parts
string strFilename = @"C:\Bethesda Car Rental\Customers.crc";
if (File.Exists(strFilename))
{
FileStream stmCustomers = new FileStream(strFilename,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
try
{
// Retrieve the list of employees from file
lstCustomers =
(Dictionary<string,
Customer>)
bfmCustomers.Deserialize(stmCustomers);
}
finally
{
stmCustomers.Close();
}
}
ShowCustomers();
}
}
}
|
private void btnNewCustomer_Click(object sender, EventArgs e)
{
CustomerEditor editor = new CustomerEditor();
Directory.CreateDirectory(@"C:\Bethesda Car Rental");
if (editor.ShowDialog() == DialogResult.OK)
{
if (editor.txtDrvLicNbr.Text == "")
{
MessageBox.Show("You must provide the driver's " +
"license number of the customer");
return;
}
if (editor.txtFullName.Text == "")
{
MessageBox.Show("You must provide the employee's full name");
return;
}
string strFilename = @"C:\Bethesda Car Rental\Customers.crc";
Customer cust = new Customer();
cust.FullName = editor.txtFullName.Text;
cust.Address = editor.txtAddress.Text;
cust.City = editor.txtCity.Text;
cust.State = editor.cbxStates.Text;
cust.ZIPCode = editor.txtZIPCode.Text;
lstCustomers.Add(editor.txtDrvLicNbr.Text, cust);
FileStream bcrStream = new FileStream(strFilename,
FileMode.Create,
FileAccess.Write,
FileShare.Write);
BinaryFormatter bcrBinary = new BinaryFormatter();
bcrBinary.Serialize(bcrStream, lstCustomers);
bcrStream.Close();
ShowCustomers();
}
}
|
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;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace BethesdaCarRental1a
{
public partial class Employees : Form
{
SortedDictionary<string, Employee> lstEmployees;
public Employees()
{
InitializeComponent();
}
internal void ShowEmployees()
{
}
private void Employees_Load(object sender, EventArgs e)
{
lstEmployees = new SortedDictionary<string, Employee>();
BinaryFormatter bfmEmployees = new BinaryFormatter();
// This is the file that holds the list of parts
string strFilename = @"C:\Bethesda Car Rental\Employees.cre";
if (File.Exists(strFilename))
{
FileStream stmEmployees = new FileStream(strFilename,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
try
{
// Retrieve the list of employees from file
lstEmployees =
(SortedDictionary<string,
Employee>)
bfmEmployees.Deserialize(stmEmployees);
}
finally
{
stmEmployees.Close();
}
}
ShowEmployees();
}
}
}
|
private void btnNewEmployee_Click(object sender, EventArgs e)
{
EmployeeEditor editor = new EmployeeEditor();
Directory.CreateDirectory(@"C:\Bethesda Car Rental");
if (editor.ShowDialog() == DialogResult.OK)
{
if (editor.txtEmployeeNumber.Text == "")
{
MessageBox.Show("You must provide an employee number");
return;
}
if (editor.txtLastName.Text == "")
{
MessageBox.Show("You must provide the employee's last name");
return;
}
string strFilename = @"C:\Bethesda Car Rental\Employees.cre";
Employee empl = new Employee();
empl.FirstName = editor.txtFirstName.Text;
empl.LastName = editor.txtLastName.Text;
empl.Title = editor.txtTitle.Text;
empl.HourlySalary = double.Parse(editor.txtHourlySalary.Text);
lstEmployees.Add(editor.txtEmployeeNumber.Text, empl);
FileStream bcrStream = new FileStream(strFilename,
FileMode.Create,
FileAccess.Write,
FileShare.Write);
BinaryFormatter bcrBinary = new BinaryFormatter();
bcrBinary.Serialize(bcrStream, lstEmployees);
bcrStream.Close();
ShowEmployees();
}
}
|
Although, or because, the key and value are distinct, to consider their combination as a single object, if you are using either the System.Collections.Hasthtable or the System.Collections.SortedList class, the .NET Framework provides the DictionaryEntry structure. To access an item, you can use the foreach loop to visit each item.
To support the foreach loop, the System.Collections.Hashtable and the System.Collections.SortedList classes implement the IEnumerable.GetEnumerator() method. In this case, the item is of type DictionaryEntry: it contains a Key and a Value in combination.
The DictionaryEntry structure contains two properties named Key and Value to identify the components of a combination. Here is an example:
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
public class Exercise : Form
{
ListBox lbxStudents;
public Exercise()
{
InitializeComponent();
}
void InitializeComponent()
{
Text = "Students";
lbxStudents = new ListBox();
lbxStudents.Location = new Point(12, 12);
Controls.Add(lbxStudents);
Load += new EventHandler(StartForm);
}
void StartForm(object sender, EventArgs e)
{
Hashtable Students = new Hashtable();
Students.Add("Hermine", "Tolston");
Students.Add("Patrick", "Donley");
Students.Add("Chrissie", "Hannovers");
Students.Add("Patricia", "Herzog");
Students["Michael"] = "Herlander";
foreach (DictionaryEntry entry in Students)
lbxStudents.Items.Add(entry.Key + " " + entry.Value);
}
}
This would produce:

If you are using a generic class, the .NET Framework provides the KeyValuePair structure that follows the same functionality as the System.Collections.DictionaryEntry structure, except that you must apply the rules of generic classes.
|
|
private void txtDrvLicNumber_Leave(object sender, EventArgs e)
{
Customer renter = null;
string strDrvLicNumber = txtDrvLicNumber.Text;
if (strDrvLicNumber.Length == 0)
{
MessageBox.Show("You must enter the renter's " +
"driver's license number");
txtDrvLicNumber.Focus();
return;
}
Dictionary<string, Customer> lstCustomers =
new Dictionary<string, Customer>();
BinaryFormatter bfmCustomers = new BinaryFormatter();
string strFilename = @"C:\Bethesda Car Rental\Customers.crc";
if (File.Exists(strFilename))
{
FileStream stmCustomers = new FileStream(strFilename,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
try
{
// Retrieve the list of customers
lstCustomers =
(Dictionary<string, Customer>)
bfmCustomers.Deserialize(stmCustomers);
if (lstCustomers.ContainsKey(strDrvLicNumber) == true)
{
foreach (KeyValuePair<string, Customer> cust in lstCustomers)
{
if (cust.Key == strDrvLicNumber)
{
renter = cust.Value;
txtCustomerName.Text = renter.FullName;
txtCustomerAddress.Text = renter.Address;
txtCustomerCity.Text = renter.City;
cbxCustomerStates.Text = renter.State;
txtCustomerZIPCode.Text = renter.ZIPCode;
}
}
}
else
{
txtCustomerName.Text = "";
txtCustomerAddress.Text = "";
txtCustomerCity.Text = "";
cbxCustomerStates.Text = "";
txtCustomerZIPCode.Text = "";
MessageBox.Show("There is no customer with that driver's " +
"license number in our database");
return;
}
}
finally
{
stmCustomers.Close();
}
}
}
|
internal void ShowEmployees()
{
if( lstEmployees.Count == 0)
return;
// Before displaying the employees, empty the list view
lvwEmployees.Items.Clear();
// This variable will allow us to identify the odd and even indexes
int i = 1;
// Use the KeyValuePair class to visit each key/value item
foreach(KeyValuePair<string, Employee> kvp in lstEmployees )
{
ListViewItem lviEmployee = new ListViewItem(kvp.Key);
Employee empl = kvp.Value;
lviEmployee.SubItems.Add(empl.FirstName);
lviEmployee.SubItems.Add(empl.LastName);
lviEmployee.SubItems.Add(empl.FullName);
lviEmployee.SubItems.Add(empl.Title);
lviEmployee.SubItems.Add(empl.HourlySalary.ToString("F"));
if( i % 2 == 0 )
{
lviEmployee.BackColor = Color.FromArgb(255, 128, 0);
lviEmployee.ForeColor = Color.White;
}
else
{
lviEmployee.BackColor = Color.FromArgb(128, 64, 64);
lviEmployee.ForeColor = Color.White;
}
lvwEmployees.Items.Add(lviEmployee);
i++;
}
}
|
internal void ShowCustomers()
{
if (lstCustomers.Count == 0)
return;
lvwCustomers.Items.Clear();
int i = 1;
foreach (KeyValuePair<string, Customer> kvp in lstCustomers)
{
ListViewItem lviCustomer = new ListViewItem(kvp.Key);
Customer cust = kvp.Value;
lviCustomer.SubItems.Add(cust.FullName);
lviCustomer.SubItems.Add(cust.Address);
lviCustomer.SubItems.Add(cust.City);
lviCustomer.SubItems.Add(cust.State);
lviCustomer.SubItems.Add(cust.ZIPCode);
if (i % 2 == 0)
{
lviCustomer.BackColor = Color.Navy;
lviCustomer.ForeColor = Color.White;
}
else
{
lviCustomer.BackColor = Color.Blue;
lviCustomer.ForeColor = Color.White;
}
lvwCustomers.Items.Add(lviCustomer);
i++;
}
}
|
![]() |
![]() |
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
![]() |
|
The Hashtable/SortedList and the Dictionary/SortedList Difference |
If you use the System.Collections.Hashtable or the System.Collections.Generic.Dictionary class to create your list, the items are cumulatively added to the collection every time you call the Add() method or when you use the indexed property to add an item. In our introduction, we saw that the optional third rule of a dictionary type of list is that the list be sorted based on the key. To spare you the hassle of manually taking care of this, the alternative is to use the SortedList class.
Whenever a new item is added to a System.Collections.SortedList variable, a System.Collections.Generic.SortedDictionary variable, or a System.Collections.Generic.SortedList variable, the list is rearranged so the collection can be sorted in either alphabetical or chronological order based on the keys. This means that, if you want your list to be logically arranged by the keys, use one of these Sorted classes to create the collection.
|
|
|
||||||||||||||||||||||||||||||||||||||||
![]() |
|
The Keys and the Values of a Collection |
After adding one or more items to the list, they are stored in two collections. The keys are stored in a collection represented by a property named Keys. The values are stored in the Values property. In the System.Collections classes, the Keys and the Values properties are of type ICollection.
To assist you with managing the keys of their collections, the System.Collections.Generic.Dictionary, the System.Collections.Generic.SortedDictionary, and the System.Collections.Generic.SortedList classes are equipped with a nested class named KeyCollection. KeyCollection is a serializable generic class that implements the ICollection<> interface. The only real functionalities of the nested KeyCollection class are its ability to know the current number of items in the list and the ability to enumerate the members of the collection through a foreach loop.
To assist you with the values of their lists, the System.Collections.Generic.Dictionary, the System.Collections.Generic.SortedDictionary, and the System.Collections.Generic.SortedList classes are equipped with the nested ValueCollection. The ValueCollection serializable class implements the ICollection<> and the IEnumerable interfaces. The functionality of the ValueCollection class is the same as its counterpart of the System.Collections namespace.
|
|
private void btnNewRentalOrder_Click(object sender, EventArgs e)
{
txtEmployeeNumber.Text = "";
txtEmployeeName.Text = "";
txtDrvLicNumber.Text = "";
txtCustomerName.Text = "";
txtCustomerAddress.Text = "";
txtCustomerCity.Text = "";
cbxCustomerStates.Text = "";
txtCustomerZIPCode.Text = "";
txtTagNumber.Text = "";
cbxCarConditions.Text = "";
txtMake.Text = "";
txtModel.Text = "";
txtCarYear.Text = "";
cbxTankLevels.Text = "Empty";
txtMileageStart.Text = "0";
txtMileageEnd.Text = "0";
dtpStartDate.Value = DateTime.Today;
dtpEndDate.Value = DateTime.Today;
txtDays.Text = "";
cbxOrderStatus.Text = "";
txtRateApplied.Text = "0.00";
txtSubTotal.Text = "0.00";
txtTaxRate.Text = "7.75";
txtTaxAmount.Text = "0.00";
txtOrderTotal.Text = "0.00";
BinaryFormatter bfmRentalOrders = new BinaryFormatter();
string strFilename = @"C:\Bethesda Car Rental\RentalOrders.cro";
if (File.Exists(strFilename))
{
FileStream stmRentalOrders = new FileStream(strFilename,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
try
{
lstRentalOrders =
(SortedList<int, RentalOrder>)
bfmRentalOrders.Deserialize(stmRentalOrders);
ReceiptNumber =
lstRentalOrders.Keys[lstRentalOrders.Count - 1] + 1;
}
finally
{
stmRentalOrders.Close();
}
}
else
{
ReceiptNumber = 100001;
lstRentalOrders = new SortedList<int, RentalOrder>();
}
txtReceiptNumber.Text = ReceiptNumber.ToString();
}
|
private void OrderProcessing_Load(object sender, EventArgs e)
{
btnNewRentalOrder_Click(sender, e);
}
|
|
Checking the Existence of an Item |
Locating an item in a dictionary type of list consists of looking for either a key, a value, or a combination of Key=Value. The Hashtable, the Dictionary, and the SortedList classes are equipped to handle these operations with little effort on your part. If you know the key of an item but want to find a value, you can use the indexed property because it produces it. Here is an example:
void StartForm(object sender, EventArgs e)
{
Hashtable Students = new Hashtable();
Students.Add("Hermine", "Tolston");
Students.Add("Patrick", "Donley");
Students.Add("Chrissie", "Hannovers");
Students.Add("Patricia", "Herzog");
Students["Michael"] = "Herlander";
foreach (DictionaryEntry entry in Students)
lbxStudents.Items.Add(entry.Key + " " + entry.Value);
string Value = (string)Students["Chrissie"];
MessageBox.Show("The value of the Chrissie key is " + Value);
}
This would produce:

To find out whether a Key/Value item exists in the list, if you are using one of the classes from the System.Collections namespace, you can call the System.Collections.Hashtable.Contains() or the System.Collections.SortedList.Contains() method. Its syntax is:
public virtual bool Contains(object key);
To look for an item, you pass its key as argument to this method. Here is an example:
void StartForm(object sender, EventArgs e)
{
Hashtable Students = new Hashtable();
Students.Add("Hermine", "Tolston");
Students.Add("Patrick", "Donley");
Students.Add("Chrissie", "Hannovers");
Students.Add("Patricia", "Herzog");
Students["Michael"] = "Herlander";
foreach (DictionaryEntry entry in Students)
lbxStudents.Items.Add(entry.Key + " " + entry.Value);
bool found = Students.Contains("Chrissie");
if (found == true)
MessageBox.Show("The list contains an item " +
"whose key is Chrissie");
else
MessageBox.Show("The list doesn't contain an " +
"item whose key is Chrissie");
found = Students.Contains("James");
if (found == true)
MessageBox.Show("The list contains an item " +
"whose key is James");
else
MessageBox.Show("The list doesn't contain an " +
"item whose key is James");
}
This would produce:
![]() |
![]() |
|
Checking the Existence of a Key |
We have seen that the System.Collections.Hashtable.Contains() and the System.Collections.SortedList.Contains() methods allow you to find out whether a collection contains a certain specific key. An alternative is to call a method named ContainsKey.
The syntax of the System.Collections.Hashtable.ContainsKey() and the System.Collections.SortedList.ContainsKey() method is:
public virtual bool ContainsKey(object key);
The syntax of the System.Collections.Generic.Dictionary.ContainsKey() and the System.Collections.Generic.SortedList.ContainsKey() method is:
public bool ContainsKey(TKey key);
|
|
private void btnSave_Click(object sender, EventArgs e)
{
if (txtReceiptNumber.Text == "")
{
MessageBox.Show("The receipt number is missing");
return;
}
// Don't save this rental order if we don't
// know who processed it
if (txtEmployeeNumber.Text == "")
{
MessageBox.Show("You must enter the employee number or the " +
"clerk who processed this order.");
return;
}
// Don't save this rental order if we don't
// know who is renting the car
if (txtDrvLicNumber.Text == "")
{
MessageBox.Show("You must specify the driver's license number " +
"of the customer who is renting the car");
return;
}
// Don't save the rental order if we don't
// know what car is being rented
if (txtTagNumber.Text == "")
{
MessageBox.Show("You must enter the tag number " +
"of the car that is being rented");
return;
}
// Create a rental order based on the information on the form
RentalOrder CurrentOrder = new RentalOrder();
CurrentOrder.EmployeeNumber = txtEmployeeNumber.Text;
CurrentOrder.OrderStatus = cbxOrderStatus.Text;
CurrentOrder.CarTagNumber = txtTagNumber.Text;
CurrentOrder.CustomerDrvLicNbr = txtDrvLicNumber.Text;
CurrentOrder.CustomerName = txtCustomerName.Text;
CurrentOrder.CustomerAddress = txtCustomerAddress.Text;
CurrentOrder.CustomerCity = txtCustomerCity.Text;
CurrentOrder.CustomerState = cbxCustomerStates.Text;
CurrentOrder.CustomerZIPCode = txtCustomerZIPCode.Text;
CurrentOrder.CarCondition = cbxCarConditions.Text;
CurrentOrder.TankLevel = cbxTankLevels.Text;
try
{
CurrentOrder.MileageStart = int.Parse(txtMileageStart.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid mileage start value");
}
try
{
CurrentOrder.MileageEnd = int.Parse(txtMileageEnd.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid mileage end value");
}
try
{
CurrentOrder.DateStart = dtpStartDate.Value;
}
catch (FormatException)
{
MessageBox.Show("Invalid start date");
}
try
{
CurrentOrder.DateEnd = dtpEndDate.Value;
}
catch (FormatException)
{
MessageBox.Show("Invalid end date");
}
try
{
CurrentOrder.Days = int.Parse(txtDays.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid number of days");
}
try
{
CurrentOrder.RateApplied = double.Parse(txtRateApplied.Text);
}
catch (FormatException)
{
MessageBox.Show("Invalid rate value");
}
CurrentOrder.SubTotal = double.Parse(txtSubTotal.Text);
try
{
CurrentOrder.TaxRate = double.Parse(txtTaxRate.Text);
}
catch (FormatException)
{
MessageBox.Show("Inavlid tax rate");
}
CurrentOrder.TaxAmount = double.Parse(txtTaxAmount.Text);
CurrentOrder.OrderTotal = double.Parse(txtOrderTotal.Text);
// The rental order is ready
// Get the receipt number from its text box
try
{
ReceiptNumber = int.Parse(txtReceiptNumber.Text);
}
catch (FormatException)
{
MessageBox.Show("You must provide a receipt number");
}
// Get the list of rental orders and
// check if there is already one with the current receipt number
// If there is already a receipt number like that...
if (lstRentalOrders.ContainsKey(ReceiptNumber) == true)
{
// Simply update its value
lstRentalOrders[ReceiptNumber] = CurrentOrder;
}
else
{
// If there is no order with that receipt,
// then create a new rental order
lstRentalOrders.Add(ReceiptNumber, CurrentOrder);
}
// The list of rental orders
string strFilename = @"C:\Bethesda Car Rental\RentalOrders.cro";
FileStream bcrStream = new FileStream(strFilename,
FileMode.Create,
FileAccess.Write,
FileShare.Write);
BinaryFormatter bcrBinary = new BinaryFormatter();
try
{
bcrBinary.Serialize(bcrStream, lstRentalOrders);
}
finally
{
bcrStream.Close();
}
}
|
|
Checking the Existence of a Value |
To find out whether a particular value exists in the list, you can call the ContainsValue() method. The syntax of the System.Collections.Hashtable.ContainsValue() and the System.Collections.SortedList.ContainsValue() method is::
public virtual bool ContainsValue(object key);
The syntax of the System.Collections.Generic.Dictionary.ContainsValue() and the System.Collections.Generic.SortedList.ContainsValue() method is:
public bool ContainsValue(TKey key);
|
Getting the Value of a Key |
The ContainsKey() method allows you to only find out whether a dictionary-based collection contains a certain key. It does not identify that key and it does not give any significant information about that key, except its existence. In some operations, first you may want to find out if the collection contains a certain key. Second, if that key exists, you may want to get its corresponding value.
To assist you with both checking the existence of a key and getting its corresponding value, the generic Dictionary, SortedDictionary, and SortedList classes are equipped with a method named TryGetValue. Its syntax is:
public bool TryGetValue(TKey key, out TValue value);
When calling this method, the first argument must be the key to look for. If that key is found, the method returns its corresponding value as the second argument passed as an out reference.
|
|
private void txtEmployeeNumber_Leave(object sender, EventArgs e)
{
Employee clerk;
string strEmployeeNumber = txtEmployeeNumber.Text;
if (strEmployeeNumber.Length == 0)
{
MessageBox.Show("You must enter the employee's number");
txtEmployeeNumber.Focus();
return;
}
SortedDictionary<string, Employee> lstEmployees =
new SortedDictionary<string, Employee>();
BinaryFormatter bfmEmployees = new BinaryFormatter();
string strFilename = @"C:\Bethesda Car Rental\Employees.cre";
if (File.Exists(strFilename))
{
FileStream stmEmployees = new FileStream(strFilename,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
try
{
// Retrieve the list of employees
lstEmployees =
(SortedDictionary<string, Employee>)
bfmEmployees.Deserialize(stmEmployees);
if (lstEmployees.TryGetValue(strEmployeeNumber, out clerk))
{
txtEmployeeName.Text = clerk.FullName;
}
else
{
txtEmployeeName.Text = "";
MessageBox.Show("There is no employee with that number");
return;
}
}
finally
{
stmEmployees.Close();
}
}
}
|
private void txtTagNumber_Leave(object sender, EventArgs e)
{
Car selected;
string strTagNumber = txtTagNumber.Text;
if (strTagNumber.Length == 0)
{
MessageBox.Show("You must enter the car's tag number");
txtTagNumber.Focus();
return;
}
Dictionary<string, Car> lstCars =
new Dictionary<string, Car>();
BinaryFormatter bfmCars = new BinaryFormatter();
string strFilename = @"C:\Bethesda Car Rental\Cars.crs";
if (File.Exists(strFilename))
{
FileStream stmCars = new FileStream(strFilename,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
try
{
// Retrieve the list of employees from file
lstCars =
(Dictionary<string, Car>)
bfmCars.Deserialize(stmCars);
if (lstCars.TryGetValue(strTagNumber, out selected))
{
txtMake.Text = selected.Make;
txtModel.Text = selected.Model;
txtCarYear.Text = selected.Year.ToString();
}
else
{
txtMake.Text = "";
txtModel.Text = "";
txtCarYear.Text = "";
MessageBox.Show("There is no car with that tag " +
"number in our database");
return;
}
}
finally
{
stmCars.Close();
}
}
}
|
private void btnOpen_Click(object sender, EventArgs e)
{
RentalOrder order = null;
if (txtReceiptNumber.Text == "")
{
MessageBox.Show("You must enter a receipt number");
return;
}
ReceiptNumber = int.Parse( txtReceiptNumber.Text);
if (lstRentalOrders.TryGetValue(ReceiptNumber, out order))
{
txtEmployeeNumber.Text = order.EmployeeNumber;
txtEmployeeNumber_Leave(sender, e);
cbxOrderStatus.Text = order.OrderStatus;
txtTagNumber.Text = order.CarTagNumber;
txtTagNumber_Leave(sender, e);
txtDrvLicNumber.Text = order.CustomerDrvLicNbr;
txtCustomerName.Text = order.CustomerName;
txtCustomerAddress.Text = order.CustomerAddress;
txtCustomerCity.Text = order.CustomerCity;
cbxCustomerStates.Text = order.CustomerState;
txtCustomerZIPCode.Text = order.CustomerZIPCode;
cbxCarConditions.Text = order.CarCondition;
cbxTankLevels.Text = order.TankLevel;
txtMileageStart.Text = order.MileageStart.ToString();
txtMileageEnd.Text = order.MileageEnd.ToString();
dtpStartDate.Value = order.DateStart;
dtpEndDate.Value = order.DateEnd;
txtDays.Text = order.Days.ToString();
txtRateApplied.Text = order.RateApplied.ToString("F");
txtSubTotal.Text = order.SubTotal.ToString("F");
txtTaxRate.Text = order.TaxRate.ToString("F");
txtTaxAmount.Text = order.TaxAmount.ToString("F");
txtOrderTotal.Text = order.OrderTotal.ToString("F");
}
else
{
MessageBox.Show("There is no rental order with that receipt number");
return;
}
}
|
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
|
![]() |
![]() |
![]() |
![]() |
|
Removing Items From a Dictionary Type of List |
To delete one item from the list, you can call the Remove() method. Its syntax is:
public virtual void Remove(object key);
Here is an example:
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
public class Exercise : Form
{
ListBox lbxStudents;
Button btnRemove;
Hashtable Students;
public Exercise()
{
InitializeComponent();
}
void InitializeComponent()
{
Text = "Students";
lbxStudents = new ListBox();
lbxStudents.Location = new Point(12, 12);
Controls.Add(lbxStudents);
btnRemove = new Button();
btnRemove.Text = "&Remove";
btnRemove.Location = new Point(12, lbxStudents.Top + lbxStudents.Height + 10);
btnRemove.Click += new EventHandler(RemoverClick);
Controls.Add(btnRemove);
Load += new EventHandler(StartForm);
}
void StartForm(object sender, EventArgs e)
{
Students = new Hashtable();
Students.Add("Hermine", "Tolston");
Students.Add("Patrick", "Donley");
Students.Add("Chrissie", "Hannovers");
Students.Add("Patricia", "Herzog");
Students["Michael"] = "Herlander";
Students["Philemon"] = "Jacobs";
Students["Antoinette"] = "Malhoun";
foreach (DictionaryEntry entry in Students)
lbxStudents.Items.Add(entry.Key + " " + entry.Value);
}
void RemoverClick(object sender, EventArgs e)
{
Students.Remove("Chrissie");
lbxStudents.Items.Clear();
foreach (DictionaryEntry entry in Students)
lbxStudents.Items.Add(entry.Key + " " + entry.Value);
}
}
This would produce:
![]() |
![]() |
To delete all items from the list, you can call the Clear() method. Its syntax is:
public virtual void Clear();
|
Exercises |
|
Bethesda Car Rental |
|
|
||
| Previous | Copyright © 2008-2009 Yevol.com | Next |
|
|
||