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:
virtual void Add(TKey key, TValue value) sealed;
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 CExercise::Start(Object ^ sender, EventArgs ^ e)
{
Hashtable ^ Students = gcnew Hashtable;
Students->Add(L"Hermine", "Tolston");
Students->Add(L"Patrick", "Donley");
}
When calling the Add() method, you must provide a
valid Key argument: it cannot be nullptr. For example, the following code would
produce an error:
void CExercise::Start(Object ^ sender, EventArgs ^ e)
{
Hashtable ^ Students = gcnew Hashtable;
Students->Add(L"Hermine", "Tolston");
Students->Add(L"Patrick", "Donley");
Students->Add(nullptr, L"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 CExercise::Start(Object ^ sender, EventArgs ^ e)
{
Hashtable ^ Students = gcnew Hashtable;
Students->Add(L"Hermine", L"Tolston");
Students->Add(L"Patrick", L"Donley");
Students->Add(L"Chrissie", L"Hannovers");
Students->Add(L"Patrick", L"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 CExercise::Start(Object ^ sender, EventArgs ^ e)
{
Hashtable ^ 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";
}
Practical
Learning: Adding Items to the Collection |
|
- Display the CarEditor form
- On the CarEditor form, double-click the Submit button and implement its
Click event as follows:
System::Void btnSubmit_Click(System::Object^ sender, System::EventArgs^ e)
{
CCar ^ vehicle = gcnew CCar;
FileStream ^ stmCars = nullptr;
BinaryFormatter ^ bfmCars = gcnew BinaryFormatter;
Directory::CreateDirectory(L"C:\\Bethesda Car Rental");
String ^ strFilename = L"C:\\Bethesda Car Rental\\Cars.crs";
if (txtTagNumber->Text->Length == 0)
{
MessageBox::Show(L"You must enter the car's tag number");
return;
}
if (txtMake->Text->Length == 0)
{
MessageBox::Show(L"You must specify the car's manufacturer");
return;
}
if (txtModel->Text->Length == 0)
{
MessageBox::Show(L"You must enter the model of the car");
return;
}
if (txtYear->Text->Length == 0)
{
MessageBox::Show(L"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 = gcnew FileStream(strFilename,
FileMode::Create,
FileAccess::Write,
FileShare::Write);
try
{
bfmCars->Serialize(stmCars, lstCars);
if (lblPictureName->Text->Length != 0)
{
FileInfo ^ flePicture = gcnew FileInfo(lblPictureName->Text);
flePicture->CopyTo(L"C:\\Bethesda Car Rental\\" +
txtTagNumber->Text +
flePicture->Extension);
}
txtTagNumber->Text = L"";
txtMake->Text = L"";
txtModel->Text = L"";
txtYear->Text = L"";
cbxCategories->Text = L"Economy";
chkCDPlayer->Checked = false;
chkDVDPlayer->Checked = false;
chkAvailable->Checked = false;
lblPictureName->Text = L".";
pbxCar->Image = nullptr;
}
finally
{
stmCars->Close();
}
}
|
- In the Solution Explorer, right-click the Customers form and click View
Code
- Change the file as follows:
#pragma once
#include "Customer.h"
#include "CustomerEditor.h"
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Collections::Generic;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO;
using namespace System::Runtime::Serialization::Formatters::Binary;
namespace BethesdaCarRental1 {
/// <summary>
/// Summary for Customers
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
/// </summary>
public ref class Customers : public System::Windows::Forms::Form
{
private:
Dictionary<String ^, CCustomer ^> ^ lstCustomers;
public:
Customers(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
void ShowCustomers()
{
}
|
- Display the Customers form and double-click an unoccupied area of its body
- Change the file as follows:
System::Void Customers_Load(System::Object^ sender, System::EventArgs^ e)
{
lstCustomers = gcnew Dictionary<String ^, CCustomer ^>;
BinaryFormatter ^ bfmCustomers = gcnew BinaryFormatter;
// This is the file that holds the list of parts
String ^ strFilename = L"C:\\Bethesda Car Rental\\Customers.crc";
if( File::Exists(strFilename))
{
FileStream ^ stmCustomers = gcnew FileStream(strFilename,
FileMode::Open,
FileAccess::Read,
FileShare::Read);
try {
// Retrieve the list of employees from file
lstCustomers =
dynamic_cast<Dictionary<String ^, CCustomer ^> ^>
(bfmCustomers->Deserialize(stmCustomers));
}
finally
{
stmCustomers->Close();
}
}
ShowCustomers();
}
|
- Return to the Customers form and double-click the New Customer button
- Implement its event as follows:
System::Void btnNewCustomer_Click(System::Object^ sender, System::EventArgs^ e)
{
CustomerEditor ^ editor = gcnew CustomerEditor;
Directory::CreateDirectory(L"C:\\Bethesda Car Rental");
if (editor->ShowDialog() == System::Windows::Forms::DialogResult::OK)
{
if (editor->txtDrvLicNbr->Text == L"")
{
MessageBox::Show(L"You must provide the driver's "
L"license number of the customer");
return;
}
if (editor->txtFullName->Text == L"")
{
MessageBox::Show(L"You must provide the employee's full name");
return;
}
String ^ strFilename = L"C:\\Bethesda Car Rental\\Customers.crc";
CCustomer ^ cust = gcnew CCustomer;
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 = gcnew FileStream(strFilename,
FileMode::Create,
FileAccess::Write,
FileShare::Write);
BinaryFormatter ^ bcrBinary = gcnew BinaryFormatter;
bcrBinary->Serialize(bcrStream, lstCustomers);
bcrStream->Close();
ShowCustomers();
}
}
|
- In the Solution Explorer, right-click the Employees and click View Code
- Change the file as follows:
#pragma once
#include "Employee.h"
#include "EmployeeEditor.h"
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Collections::Generic;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO;
using namespace System::Runtime::Serialization::Formatters::Binary;
namespace BethesdaCarRental1 {
/// <summary>
/// Summary for Employees
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
/// </summary>
public ref class Employees : public System::Windows::Forms::Form
{
private:
SortedDictionary<String ^, CEmployee ^> ^ lstEmployees;
public:
Employees(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
void ShowEmployees()
{
}
|
- Display the Employees form and double-click an unoccupied area of its body
- Change the file as follows:
System::Void Employees_Load(System::Object^ sender, System::EventArgs^ e)
{
lstEmployees = gcnew SortedDictionary<String ^, CEmployee ^>;
BinaryFormatter ^ bfmEmployees = gcnew BinaryFormatter;
// This is the file that holds the list of parts
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 from file
lstEmployees =
dynamic_cast<SortedDictionary<String ^, CEmployee ^> ^>
(bfmEmployees->Deserialize(stmEmployees));
}
finally
{
stmEmployees->Close();
}
}
ShowEmployees();
}
|
- Return to the Employees form and double-click the New Employee button
- Implement its event as follows:
System::Void btnNewEmployee_Click(System::Object^ sender, System::EventArgs^ e)
{
EmployeeEditor ^ editor = gcnew EmployeeEditor;
Directory::CreateDirectory("C:\\Bethesda Car Rental");
if (editor->ShowDialog() == System::Windows::Forms::DialogResult::OK)
{
if (editor->txtEmployeeNumber->Text == L"")
{
MessageBox::Show(L"You must provide an employee number");
return;
}
if (editor->txtLastName->Text == L"")
{
MessageBox::Show(L"You must provide the employee's last name");
return;
}
String ^ strFilename = "C:\\Bethesda Car Rental\\Employees.cre";
CEmployee ^ empl = gcnew CEmployee;
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 = gcnew FileStream(strFilename,
FileMode::Create,
FileAccess::Write,
FileShare::Write);
BinaryFormatter ^ bcrBinary = gcnew BinaryFormatter;
bcrBinary->Serialize(bcrStream, lstEmployees);
bcrStream->Close();
ShowEmployees();
}
}
|
- Save all