Home

Introduction to Databases:
Operations on an Array

 
 

Introduction

Because an array is primarily a series of objects or values, there are various pieces of information you would get interested to get from it. Typical operations include:

  • Adding elements to the array
  • Re-arranging the list or the order of elements in the array.
  • Finding out whether the array contains a certain element
  • If the array contains a certain element, what index that element has

Although you can write your own routines to perform these operations, the Array class provides most of the methods you would need to get the necessary information.

Practical Learning: Introducing Operations on Arrays

  1. To create a new form, on the main menu, click Project -> Add New Item...
  2. Click Windows Form
  3. Set the name to CustomerTransactions and press Enter
  4. Design the form as follows:
     
    Customer Transactions
     
    Control Text Name Other Properties
    Label Label View Transactions For:    
    MaskedTextBox MaskedTextBox   txtAccountNumber Mask: 00-000000-00
    Button Button Find btnFind  
    ListView List View   lvwTransactions FullRowSelect: True
    GridLines: True
    View: Details
    Columns
    (Name) Text TextAlign Width
    colIndex #   25
    colTransactionDate Trans Date Center 80
    colProcessedBy Processed By Center 80
    colTransactionType Trans Type   90
    colDeposit Deposit Right  
    colWithdrawal Withdrawal Right 65
    colChargeAmount Charge Right 50
    Label Label Total Deposits:    
    TextBox TextBox   txtTotalDeposits Text: 0.00
    TextAlign: Right
    Label Label Total Charges:    
    TextBox TextBox   txtTotalCharges Text: 0.00
    TextAlign: Right
    Label Label Total Withdrawals:    
    TextBox TextBox   txtTotalWithdrawals Text: 0.00
    TextAlign: Right
    Label Label Balance:    
    TextBox TextBox   txtBalance Text: 0.00
    TextAlign: Right
    Button Button Close btnClose  
  5. Display the first form (Form1) and complete its design as follows:
     
    Yugo National Bank
    Button Text Name
    Button Employees btnEmployees
    Button Customers btnCustomers
    Button Transactions btnTransactions
    Button Customer Records btnCustomerRecords
    Button Close btnClose
  6. Double-click the Customer Records button
  7. In the top section of the file, include the CustomerTransactions.h header file:
     
    #pragma once
    #include "Employee.h"
    #include "Employees.h"
    #include "AccountsRecords.h"
    #include "Customer.h"
    #include "Customers.h"
    #include "CustomersTransactions.h"
    #include "CustomerTransactions.h"
    
    namespace YugoNationalBank1 {
  8. Implement the btnCustomerRecords_Click event as follows:
     
    System::Void btnCustomerRecords_Click(System::Object^  sender,
    				      System::EventArgs^  e)
    {
        CustomerTransactions ^ CustRecords = gcnew CustomerTransactions;
        CustRecords->ShowDialog();
    }
  9. Return to the form (Form1) and double-click the Close button
  10. Implement its event as follows:
     
    System::Void btnClose_Click(System::Object^  sender, System::EventArgs^  e)
    {
        Close();
    }
  11. Execute the application to test it
  12. Close the forms and return to your programming environment

Adding an Element to an Array

We have seen that, using the [] operator, you can add a new element to an array. Still, to support this operation, the Array class is equipped with the SetValue() method that is overloaded with various versions. Here is an example that adds an element to the third position of the array:

Array

File: Exercise.h

#pragma once

#include "Person.h"

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

namespace Exercise1 {

	/// <summary>
	/// Summary for Exercise
	///
	/// 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 Exercise : public System::Windows::Forms::Form
	{
		array<CPerson ^> ^ People;
		array<CPerson ^> ^ ArrayInitializer();
		void ShowPeople(array<CPerson ^> ^ People);

	public:
		Exercise(void)
		{
			InitializeComponent();
			//
			//TODO: Add the constructor code here
			//
		}

	protected:
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		~Exercise()
		{
			if (components)
			{
				delete components;
			}
		}

	. . . No Change

	private:
		/// <summary>
		/// Required designer variable.
		/// </summary>
		System::ComponentModel::Container ^components;

#pragma 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>
		void InitializeComponent(void)
		{
			. . . No Change
		}
#pragma endregion
	private: System::Void Exercise_Load(System::Object^  sender, System::EventArgs^  e)
			 {
				 array<CPerson ^> ^ persons = ArrayInitializer();
				 ShowPeople(persons);
			 }

private: System::Void btnAdd_Click(System::Object^  sender, System::EventArgs^  e)
		 {
			 CPerson ^ pers = gcnew CPerson;

			 pers->PersonID = int::Parse(txtPersonID->Text);
			 pers->FirstName = txtFirstName->Text;
			 pers->LastName = txtLastName->Text;
			 if (cbxGenders->Text == L"Male")
				 pers->Gender = L"Male";
			 else if (cbxGenders->Text == L"Female")
				 pers->Gender = L"Female";
			 else
				 pers->Gender = L"Unknown";

			 People->SetValue(pers, pers->PersonID);
			 ShowPeople(People);
		 }
};
}

File: Exercise.cpp

#include <windows.h>
#include "Exercise.h"

namespace Exercise1
{
	array<CPerson ^> ^ Exercise::ArrayInitializer()       
	{
		People = gcnew array<CPerson ^>(8);

		for(int i = 0; i < 8; i++)
		{
			People[i] = gcnew CPerson;
			People[i]->PersonID = 0;
			People[i]->FirstName = L"";
			People[i]->LastName = L"";
			People[i]->Gender = L"Unknown";
		}

		return People;
	}

	void Exercise::ShowPeople(array<CPerson ^> ^ People)
	{
		lvwPeople->Items->Clear();

		for each(CPerson ^ pers in People)
		{
		ListViewItem ^ lviPerson = 
			gcnew ListViewItem(pers->PersonID->ToString());

			lviPerson->SubItems->Add(pers->FirstName);
			lviPerson->SubItems->Add(pers->LastName);
			lviPerson->SubItems->Add(pers->Gender);

			lvwPeople->Items->Add(lviPerson);
		}
	}
}

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
					 LPSTR lpCmdLine, int nCmdShow)
{
	Application::Run(gcnew CExercise1::Exercise);
	return 0;
}

When the Array::SetValue() method is called, it replaces the element at the indicated position.

Getting an Element From an Array

The reverse of adding an item to an array is to retrieve one. You can do this with the [] operator. To support this operation, the Array class is equipped with the GetValue() method that comes in various versions. Here is an example of calling it:

System::Void lvwPeople_ItemSelectionChanged(System::Object^  sender,
	System::Windows::Forms::ListViewItemSelectionChangedEventArgs^  e)
{
    CPerson ^ pers = static_cast<CPerson ^>(People->GetValue(e->ItemIndex));

    txtPersonID->Text = pers->PersonID->ToString();
    txtFirstName->Text = pers->FirstName;
    txtLastName->Text = pers->LastName;
    cbxGenders->Text = pers->Gender->ToString();
}

When calling this method, make sure you provide a valid index, if you do not, you would get an IndexOutOfRangeException exception.

 

 

 

Checking the Existence of an Element

Once some elements have been added to an array, you can try to locate one. One of the most fundamental means of looking for an item consists of finding out whether a certain element exists in the array. To support this operation, the Array class is equipped with the Exists() method whose syntax is:

public:
    generic<typename T>
    static bool Exists(
    	array<T>^ array, 
    	Predicate<T>^ match);

This is a generic method that takes two arguments. The first argument is the array on which you will look for the item. The second argument is a delegate that specifies the criterion to apply.

Finding an Element

One of the most valuable operations you can perform on an array consists of looking for a particular element. To assist you with this, the Array class is equipped with the Find() method. Its syntax is:

public:
    generic<typename T>
    static T Find(
    	array<T>^ array, 
    	Predicate<T>^ match
    );

This generic method takes two arguments. The first argument is the name of the array that holds the elements. The second argument is a delegate that has the criterion to be used to find the element.

Practical Learning: Finding an Element

  1. Access the Customer Transactions form
  2. Double-click the Find button
  3. In the top section of the file, include the AccountsRecords.h header file:
     
    #pragma once
    
    #include "Customer.h"
    #include "AccountsRecords.h"
  4. Implement the Click event as follows:
     
    System::Void btnFind_Click(System::Object^  sender, System::EventArgs^  e)
    {
        double TotalDeposits = 0;
        double TotalWithdrawals = 0;
        double TotalCharges = 0;
        double Balance;
        bool AccountFound = false;
        CCustomer ^ CustomerFound = nullptr;
    
        AccountNumber = txtAccountNumber->Text;
        array<CCustomer ^> ^ Accounts = CAccountsRecords::GetCustomers();
        array<CAccountTransaction ^> ^ Trans = CAccountsRecords::GetTransactions();
    
        for each(CCustomer ^ Cust in Accounts)
        {
    	if( Cust->AccountNumber == AccountNumber )
    	{
    		CustomerFound = Cust;
    		AccountFound = true;
    	}
        }
    
        if (AccountFound == true)
        {
            int i = 1;
            lvwTransactions->Items->Clear();
    
            for each(CAccountTransaction ^ ActTrans in Trans)
            {
                if (ActTrans->ProcessedFor == AccountNumber)
                {
                    ListViewItem ^ lviTransactions = 
    			gcnew ListViewItem(i.ToString());
    
                    lviTransactions->SubItems->Add(
    			ActTrans->TransactionDate.ToString(L"dd-MMM-yyyy"));
    
                    if (ActTrans->ProcessedBy == 0)
                        lviTransactions->SubItems->Add(L"");
                    else
                        lviTransactions->SubItems->Add(
    			ActTrans->ProcessedBy.ToString());
    
                    lviTransactions->SubItems->Add(
    			ActTrans->TransactionType->ToString());
    
                    if (ActTrans->DepositAmount == 0)
                        lviTransactions->SubItems->Add(L"");
                    else
                        lviTransactions->SubItems->Add(
    			ActTrans->DepositAmount.ToString(L"F"));
    
                    if (ActTrans->WithdrawalAmount == 0)
                        lviTransactions->SubItems->Add(L"");
                    else
                        lviTransactions->SubItems->Add(
    			ActTrans->WithdrawalAmount.ToString(L"F"));
    
                    if (ActTrans->ChargeAmount == 0)
                        lviTransactions->SubItems->Add(L"");
                    else
                        lviTransactions->SubItems->Add(
    			ActTrans->ChargeAmount.ToString(L"F"));
    
                    lvwTransactions->Items->Add(lviTransactions);
    
                    i++;
                }
            }
    
            for each( ListViewItem ^ lviTransaction in lvwTransactions->Items)
            {
                if( lviTransaction->SubItems[4]->Text != L"" )
                    TotalDeposits = TotalDeposits + 
    			double::Parse(lviTransaction->SubItems[4]->Text);
                if( lviTransaction->SubItems[5]->Text != L"" )
                    TotalWithdrawals = TotalWithdrawals + 
    			double::Parse(lviTransaction->SubItems[5]->Text);
                if( lviTransaction->SubItems[6]->Text != L"" )
                    TotalCharges = TotalCharges + 
    			double::Parse(lviTransaction->SubItems[6]->Text);
            }
    
            Balance = TotalDeposits - (TotalWithdrawals + TotalCharges);
            txtTotalDeposits->Text = TotalDeposits.ToString(L"F");
            txtTotalWithdrawals->Text = TotalWithdrawals.ToString(L"F");
            txtTotalCharges->Text = TotalCharges.ToString(L"F");
            txtBalance->Text = Balance.ToString(L"F");
        }
        else
            MessageBox::Show(L"There is no customer with that account number");
    }
  5. Return to the Account Transactions form and double-click the Close button
  6. Implement its event as follows:
     
    System::Void btnClose_Click(System::Object^  sender, System::EventArgs^  e)
    {
        Close();
    }
  7. Execute the application to test it
 
 
   
 

Previous Copyright © 2009-2010 FunctionX, Inc. Next