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:
virtual bool ContainsKey(TKey key) sealed;
Practical
Learning: Checking the Existence of a Key |
|
- On the Order Processing form, double-click the Save button and implement its event as follows:
System::Void btnSave_Click(System::Object^ sender, System::EventArgs^ e)
{
if(txtReceiptNumber->Text == L"")
{
MessageBox::Show(L"The receipt number is missing");
return;
}
// Don't save this rental order if we don't
// know who processed it
if(txtEmployeeNumber->Text == L"")
{
MessageBox::Show(L"You must enter the employee number or the "
L"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 == L"")
{
MessageBox::Show(L"You must specify the driver's license number "
L"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 == L"")
{
MessageBox::Show(L"You must enter the tag number "
L"of the car that is being rented");
return;
}
// Create a rental order based on the information on the form
CRentalOrder ^ CurrentOrder = gcnew CRentalOrder;
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(L"Invalid mileage start value");
}
try
{
CurrentOrder->MileageEnd = int::Parse(txtMileageEnd->Text);
}
catch(FormatException ^)
{
MessageBox::Show(L"Invalid mileage end value");
}
try
{
CurrentOrder->DateStart = dtpStartDate->Value;
}
catch(FormatException ^)
{
MessageBox::Show(L"Invalid start date");
}
try {
CurrentOrder->DateEnd = dtpEndDate->Value;
}
catch(FormatException ^)
{
MessageBox::Show(L"Invalid end date");
}
try {
CurrentOrder->Days = int::Parse(txtDays->Text);
}
catch(FormatException ^)
{
MessageBox::Show(L"Invalid number of days");
}
try {
CurrentOrder->RateApplied = double::Parse(txtRateApplied->Text);
}
catch(FormatException ^)
{
MessageBox::Show(L"Invalid rate value");
}
CurrentOrder->SubTotal = double::Parse(txtSubTotal->Text);
try {
CurrentOrder->TaxRate = double::Parse(txtTaxRate->Text);
}
catch(FormatException ^)
{
MessageBox::Show(L"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(L"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 = L"C:\\Bethesda Car Rental\\RentalOrders.cro";
FileStream ^ bcrStream = gcnew FileStream(strFilename,
FileMode::Create,
FileAccess::Write,
FileShare::Write);
BinaryFormatter ^ bcrBinary = gcnew BinaryFormatter;
try
{
bcrBinary->Serialize(bcrStream, lstRentalOrders);
}
finally
{
bcrStream->Close();
}
}
|
- Save the file
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^ value);
The syntax of the System::Collections::Generic::Dictionary::ContainsValue()
and the System::Collections::Generic::SortedList::ContainsValue() method is:
public:
bool ContainsValue(TValue value);
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:
virtual bool TryGetValue(TKey key,
[OutAttribute] TValue% value) sealed;
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.
Practical
Learning: Getting the Value of a Key |
|
- On the Order Processing form, click the Employee Number text box
- In the Events section of the Properties window, double-click Leave and
implement the event as follows:
System::Void txtEmployeeNumber_Leave(System::Object^ sender,
System::EventArgs^ e)
{
CEmployee ^ clerk;
String ^ strEmployeeNumber = txtEmployeeNumber->Text;
if (strEmployeeNumber->Length == 0)
{
MessageBox::Show(L"You must enter the employee's number");
txtEmployeeNumber->Focus();
return;
}
SortedDictionary<String ^, CEmployee ^> ^ lstEmployees =
gcnew SortedDictionary<String ^, CEmployee ^>;
BinaryFormatter ^ bfmEmployees = gcnew BinaryFormatter;
String ^ strFilename = L"C:\\Bethesda Car Rental\\Employees.cre";
if( File::Exists(strFilename))
{
FileStream ^ stmEmployees = gcnew FileStream(strFilename,
FileMode::Open,
FileAccess::Read,
FileShare::Read);
try {
// Retrieve the list of employees
lstEmployees =
dynamic_cast<SortedDictionary<String ^, CEmployee ^> ^>
(bfmEmployees->Deserialize(stmEmployees));
if (lstEmployees->TryGetValue(strEmployeeNumber, clerk))
{
txtEmployeeName->Text = clerk->FullName;
}
else
{
txtEmployeeName->Text = L"";
MessageBox::Show(L"There is no employee with that number");
return;
}
}
finally
{
stmEmployees->Close();
}
}
}
|
- Return to the Order Processing form and click the Tag Number text box
- In the Events section of the Properties window, double-click Leave and
implement the event as follows:
System::Void txtTagNumber_Leave(System::Object^ sender,
System::EventArgs^ e)
{
CCar ^ selected;
String ^ strTagNumber = txtTagNumber->Text;
if (strTagNumber->Length == 0)
{
MessageBox::Show(L"You must enter the car's tag number");
txtTagNumber->Focus();
return;
}
Dictionary<String ^, CCar ^> ^ lstCars =
gcnew Dictionary<String ^, CCar ^>;
BinaryFormatter ^ bfmCars = gcnew BinaryFormatter;
String ^ strFilename = L"C:\\Bethesda Car Rental\\Cars.crs";
if( File::Exists(strFilename))
{
FileStream ^ stmCars = gcnew FileStream(strFilename,
FileMode::Open,
FileAccess::Read,
FileShare::Read);
try
{
// Retrieve the list of employees from file
lstCars =
dynamic_cast<Dictionary<String ^, CCar ^> ^>
(bfmCars->Deserialize(stmCars));
if (lstCars->TryGetValue(strTagNumber, selected))
{
txtMake->Text = selected->Make;
txtModel->Text = selected->Model;
txtCarYear->Text = selected->Year.ToString();
}
else
{
txtMake->Text = L"";
txtModel->Text = L"";
txtCarYear->Text = L"";
MessageBox::Show(L"There is no car with that tag "
L"number in our database");
return;
}
}
finally
{
stmCars->Close();
}
}
}
|
- Display the Order Processing form and double-click the Open button
- Implement its event as follows:
System::Void btnOpen_Click(System::Object^ sender, System::EventArgs^ e)
{
CRentalOrder ^ order = nullptr;
if (txtReceiptNumber->Text == L"")
{
MessageBox::Show(L"You must enter a receipt number");
return;
}
ReceiptNumber = int::Parse( txtReceiptNumber->Text);
if (lstRentalOrders->TryGetValue(ReceiptNumber, 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(L"F");
txtSubTotal->Text = order->SubTotal.ToString(L"F");
txtTaxRate->Text = order->TaxRate.ToString(L"F");
txtTaxAmount->Text = order->TaxAmount.ToString(L"F");
txtOrderTotal->Text = order->OrderTotal.ToString(L"F");
}
else
{
MessageBox::Show(L"There is no rental order with that receipt number");
return;
}
}
|
- Return to the Order Processing form
- Double-click the Close button and implement the event as follows:
System::Void btnClose_Click(System::Object^ sender, System::EventArgs^ e)
{
Close();
}
|
- Execute the application
- Create a few rental orders and print them
- Close the forms and return to your programming environment
- Execute the application again
- Open a previously created order to simulate a customer returning a car and
change some values on the form such as the return date, the mileage end, and
the order status
- Also click the Calculate button to get the final evaluation
- Print the rental orders
- Close the forms and return to your programming environment
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:
#pragma once
#include <windows.h>
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Drawing;
using namespace System::Collections;
using namespace System::Windows::Forms;
public ref class CExercise : public Form
{
private:
ListBox ^ lbxStudents;
Button ^ btnRemove;
Hashtable ^ Students;
void InitializeComponent();
void Start(Object ^ sender, EventArgs ^ e);
void RemoverClick(Object ^ sender, EventArgs ^ e);
public:
CExercise();
};
CExercise::CExercise()
{
InitializeComponent();
}
void CExercise::InitializeComponent()
{
Text = L"Students";
Size = Drawing::Size(150, 175);
StartPosition = FormStartPosition::CenterScreen;
Load += gcnew EventHandler(this, &CExercise::Start);
lbxStudents = gcnew ListBox;
lbxStudents->Location = Point(12, 12);
Controls->Add(lbxStudents);
btnRemove = gcnew Button();
btnRemove->Text = L"&Remove";
btnRemove->Location = Point(12, lbxStudents->Top + lbxStudents->Height + 10);
btnRemove->Click += gcnew EventHandler(this, &CExercise::RemoverClick);
Controls->Add(btnRemove);
}
void CExercise::Start(Object ^ sender, EventArgs ^ e)
{
Students = gcnew Hashtable;
Students->Add(L"Hermine", "Tolston");
Students->Add(L"Patrick", "Donley");
Students->Add(L"Chrissie", "Hannovers");
Students->Add(L"Patricia", "Herzog");
Students[L"Michael"] = L"Herlander";
Students[L"Philemon"] = L"Jacobs";
Students[L"Antoinette"] = L"Malhoun";
for each(DictionaryEntry ^ entry in Students)
lbxStudents->Items->Add(entry->Key + L" " + entry->Value);
}
void CExercise::RemoverClick(Object ^ sender, EventArgs ^ e)
{
Students->Remove(L"Chrissie");
lbxStudents->Items->Clear();
for each(DictionaryEntry ^ entry in Students)
lbxStudents->Items->Add(entry->Key + L" " + entry->Value);
}
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
Application::Run(gcnew CExercise());
return 0;
}
This would produce:
To delete all items from the list, you can call the Clear()
method. Its syntax is:
public:
virtual void Clear();
- Create a Windows Application named BethesdaCarRental1a
When writing any code that has to do with lists, use a class from the System::Collections
namespace
- Create a class named Employee that will hold the following pieces of
information about each employee: the employee number, the date hired, the
first name, the middle name, the last name, the home address, the city, the
state, the ZIP (or postal) code, the marital status, the title, the email
address, the home telephone number, the cell phone number, the work
telephone number, the extension, and the hourly salary
- Create a form named EmployeeEditor and design it so that it includes:
- A text box for the employee number, the date hired, the first name,
the middle name, the last name, the home address, the city, the ZIP (or
postal) code, the title, the email address, the home telephone number,
the cell phone number, the work telephone number, the extension, and the
hourly salary
- A combo box for the state (the items must include all US states and
all Canadian provinces in 2-letter abbreviation each), the marital
status (the items will include Single no Children, Single Parent,
Married no Children, Married With Children, Separated, Widow, Other)
- Create a form named Employees and that will be used to show some
information about each employee of the company, including the employee
number, the date hired, the full name (it will consist of the last name,
followed by a comma, followed by the first name), the marital status, the
title, and the hourly salary.
|
|