Home

Windows Controls: The Combo Box

   

Introduction to the Combo Box

 

Description

A combo box is a text box that compines an edit control and a down-pointing arrow button. Here are examples (the Font Color, the Effects, the Relief, the Overlining, the Overline Color, the Strikethrough, the Underlining, and the Underline color combo boxes):

Character

Like a list box, a combo box holds a list of items. Unlike a list box, there is a version of a combo box that retracts once the user has made a selection. This is useful when space saving is particularly important.

Practical LearningPractical Learning: Introducing Combo Boxes

  1. Start Embarcadero RAD Studio
  2. To create a new application, on the main menu, click File -> New -> VCL Forms Application - C++Builder
  3. In the Object Inspector, change the following properties:
    Caption: Clarskville Ice Cream
    Name:    frmIceCream
    Position: poScreenCenter
  4. In the Standard section of the Tool Palette, click TMainMenu TMainMenu and click the form
  5. On the form, right-click TMainMenu1 and click Menu Designer...
  6. Right-click inside the Menu Designer and click Insert From Template...
  7. In the Insert Template dialog box, click File Menu
  8. Click OK
  9. To save the project, on the main menu, click File -> Save All
  10. Click New Folder
  11. Type ClarksvilleIceCream1 as the name of the folder and press Enter twice to display the contents of that folder
  12. Change the unit file to IceCream and click Save
  13. Change the project name to ClarksvilleIceCream and click Save

Creating a Combo Box

To suppport combo boxes, the VCL provides a class named TComboBox, which implements the TCustomComboBox class. The TCustomComboBox class is derived from TCustomCombo. The TCustomCombo class is based on TCustomListControl:

TComboBox Inheritance

To visuall add a combo box to your application, from the Standard section of the Tool Palette, click the TComboBox button TComboBox and click the form. You can then resize or reposition the control to the desired location.

The TComboBox as a class has only its constructor and its destructor as methods. Its other methods are derived from the parent TCustomComboBox class. The TComboBox constructor is used to dynamically create an instance of the class. If you cannot add the control at design time, declare a pointer to TComboBox and use the new operator to assign the controlís owner for cleaning purposes:

//---------------------------------------------------------------------------
void __fastcall TForm1::btnCreateComboBoxClick(TObject *Sender)
{
	TComboBox *CarMake = new TComboBox(this);
	CarMake->Parent = this;
}
//---------------------------------------------------------------------------

Practical LearningPractical Learning: Creating Combo Boxes

  • Design the form as follows:
     
    Clarksville Ice Cream: Form Design
    Control Alignment Caption DateFormat Name Text
    TBevel GroupBox          
    TLabel Label   Order &Date:      
    TDateTimePicker TDateTimePicker     dfLong dtpOrderDate  
    TLabel Label Order &Time:
    TDateTimePicker TDateTimePicker       dtpOrderTime  
    TLabel Label   &Flavor:      
    TComboBox ComboBox       cbxFlavors  
    TLabel Label   Con&tainer:      
    TComboBox ComboBox       cbxContainers  
    TLabel Label   &Ingredient:      
    TComboBox ComboBox       cbxIngredients  
    TLabel Label   Sc&oops:      
    TEdit ListBox taRightJustify     edtScoops 0
    TButton Button   C&alculate   btnCalculate  
    TLabel Label   Total:      
    TEdit ListBox taRightJustify     edtOrderTotal 0.00

Characteristics of a Combo Box

 

Introduction

 

The combo box was one the earliest controls of Microsoft Windows. It gets all its primary visual characteristics from its ancestors, the TControl and the TWinControl classes. Therefore, after adding a combo box to a form, you can manipulate its properties to change the default values. If you create a local list, you will manipulate it in the same function or event:

//---------------------------------------------------------------------------
void __fastcall TForm1::btnCreateComboBoxClick(TObject *Sender)
{
	TComboBox *CarMake = new TComboBox(this);
	CarMake->Parent = this;

	CarMake->Left = 32;
	CarMake->Top = 16;
}
//---------------------------------------------------------------------------

Just like every control of your application, the name is the most important property of the control, for you and the compiler. This name allows you and the compiler to refer to the control. By default, the first combo box you visually add to your form at design time is called ComBox1, the second would be ComboBox2, etc. To change the name of the control, click the Name field, type a new name and press Enter (or click somewhere else).

The Strings of a Combo Box

Probably the first thing the user sees on a combo box is the text it displays. Although the text of an item is a UnicodeString, the items are composed from the TStrings class. To create this list, when the control is selected on the form, on the Object Inspector, click the Items field to reveal an ellipsis button. Click the ellipsis button to display the String List Editor. When you click OK, the control would be filled with the new items. You can also fill out the control using the methods of the TStrings class. For example, to create a list of items, you could write:

//---------------------------------------------------------------------------
void __fastcall TForm1::btnFillTheListClick(TObject *Sender)
{
    CarMake->Items->Add("Ford");
    CarMake->Items->Add("Honda");
    CarMake->Items->Add("Dodge");
    CarMake->Items->Add("BMW");
}
//---------------------------------------------------------------------------

By default, the items you add to the combo box will appear in the order they are supplied. For example the TStrings::Add() method would add the new string at the end of the list. If you want the list of items to be sorted, you can change the value of the Sorted property from false (the default) to true. To sort a list programmatically, you can write:

//---------------------------------------------------------------------------
void __fastcall TForm1::btnSortTheListClick(TObject *Sender)
{
    CarMake->Sorted = True;
}
//---------------------------------------------------------------------------

You can un-sort the list by changing the value of the Sorted property. This property works exactly like its equivalent in the TListBox control.

Practical LearningPractical Learning: Adding Items to a Combo Box

  1. To create a list of items, on the form, click the Flavor combo box (the combo box on the right side of the Flavor label)
  2. In the Object Inspector, click Items and click its ellipsis button
  3. In the String List Editor, type Other and press Enter
  4. Complete the list with the following items:
     
    Other
    Vanilla
    Cherry Coke
    Butter Pecan
    Chunky Butter
    Chocolate Chip
    Caramel Au Lait
    Cream of Cocoa
    Chocolate Cookie
    Organic Strawberry
    Chocolate Brownies

     
    String Collection Editor
  5. Click OK
  6. Click the Container combo box
  7. In the Object Inspector, click Items and click its button
  8. Type the following values:
     
    Cup
    Bowl
    Cone
    Other
  9. Click OK
  10. Click the Ingredient combo box
  11. In the Object Inspector, click Items and click its ellipsis button
  12. Type the following values:
     
    None
    M & M
    Cookies
    Peanuts
    Mixed Nuts
  13. Click OK
  14. To start a new project, on the main menu, click File -> New -> VCL Forms Application - C++Builder
  15. When asked whether you want to save, click Yes
  16. In the Object Inspector, change the following properties:
    Caption: College Park Auto Parts
    Name:    frmInventory
    Position: poScreenCenter
  17. To save the project, on the main menu, click File -> Save All
  18. Click New Folder
  19. Type CollegeParkAutoParts1 as the name of the folder and press Enter twice to display the contents of that folder
  20. Change the unit file to Inventory and click Save
  21. Change the project name to CollegeParkAutoParts and click Save
  22. Design the form as follows:
     
    College Park Auto Parts - Form Design
    Control Caption Kind  Name
    TGroupBox GroupBox Part Selection    
    TLabel Label Year:    
    TLabel Label Make:    
    TLabel Label Model:    
    TLabel Label Item Category:    
    TComboBox ComboBox     cbxYears
    TComboBox ComboBox     cbxMakes
    TComboBox ComboBox     cbxModels
    TComboBox ComboBox     cbxCategories
    TGroupBox GroupBox Available Parts    
    TStringGrid TStringGrid     grdAvailableParts
    TBitBtn Button   bkClose  
  23. To create a list of items using the Add() method, double-click an unoccupied area of the form and implement its Load event as follows:
    //---------------------------------------------------------------------------
    void __fastcall TfrmInventory::FormCreate(TObject *Sender)
    {
    	TDateTime Today = Date();
    	unsigned short Year, Month, Day;
    
    	Today.DecodeDate(&Year, &Month, &Day);
    
    	for (int i = Year; i >= 1960; i--)
    		cbxYears->Items->Add(i);
    
    	grdAvailableParts->ColWidths[0] = 60;
    	grdAvailableParts->ColWidths[1] = 260;
    	grdAvailableParts->ColWidths[2] = 70;
    
    	grdAvailableParts->Cells[0][0]  = L"Item #";
    	grdAvailableParts->Cells[1][0]  = L"Item Name";
    	grdAvailableParts->Cells[2][0]  = L"Unit Price";
    }
    //---------------------------------------------------------------------------
    
  24. Execute the application to test it
     
    College Park Auto Parts - Form Design
     
    College Park Auto Parts - Form Design
  25. Close the form and return to your programming environment

Using a Combo Box

There are two mains operations a user will perform on a combo box: selecting an item from the list or changing the content of the list. Many of the events that occur during the use of a combo box are from other controls or actions that are not programmatically directly related to a combo box. It is usually possible to fill out the list of a combo box at design time, that is, if you know the list of items that will be used. Otherwise, you will use another event or function to provide the items of the list. For example, the OnCreate event of a form is a common place to fill out a list, especially if you want the list to own its items the first time it appears to the user. If you create a combo box named cbxSports but do not provide its items at design time, you can use the OnCreate event of the hosting form to fill it up as follows:

//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
	cbxMajor->Items->Add("Accounting");
	cbxMajor->Items->Add("Medical Assistant");
	cbxMajor->Items->Add("Fire Science");
	cbxMajor->Items->Add("Computer Sciences");
	cbxMajor->Items->Add("Business Administration");
	cbxMajor->Items->Add("Hospitality Management");
	cbxMajor->Items->Add("Criminal Justice");
	cbxMajor->Items->Add("Computer Technician");
	cbxMajor->Items->Add("Cartography");
	cbxMajor->Items->Add("Music");
	cbxMajor->ItemIndex = 3;
}
//---------------------------------------------------------------------------

The most regular operation a user performs on a combo box is to select an item from the list. This happens when the user clicks the arrow to expand the list and then clicks one item. Once the user clicks one of the items, the list disappears and the combo box becomes a regular edit box (unless the style of the combo box is csSimple). Using this event, you can find out what item the user would have selected and act accordingly. For example, you can transfer the selected item to another control such as an edit box. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::cbxMajorClick(TObject *Sender)
{
	edtMajor->Text = cbxMajor->Items->Strings[cbxMajor->ItemIndex].c_str();
}
//---------------------------------------------------------------------------

The OnChange event occurs when the user changes the item that was displaying in the edit box of the combo box. Also this event occurs in response to the user making a selection. It is more appropriate if you allow the user to edit an item of the list or if you allow the user to add items to the list by typing directly in the edit box. Like the edit control, the OnChange event occurs immediately as the user types anything in the edit box portion of the combo box. The OnClick event cannot respond to these events. You can use the OnChange event to deal with the user trying to modify the item on the edit box. You can also use it to respond to other actions associated with the user making a selection. For example, you can simply display the list the number of items in the list:

//---------------------------------------------------------------------------
void __fastcall TForm1::cbxMajorChange(TObject *Sender)
{
    edtCount->Text = IntToStr(cbxMajor->Items->Count);
}
//---------------------------------------------------------------------------
 
 
 

Practical LearningPractical Learning: Selecting an Item

  1. On the main menu, click File -> New -> Unit - C++Builder
  2. To save it, on the Standard toolbar, click the Save All button Save All
  3. Set the name to PartDescription
  4. Click Save
  5. Change the PartDescription.h header file as follows:
    //---------------------------------------------------------------------------
    
    #ifndef PartDescriptionH
    #define PartDescriptionH
    #define <vcl.h>
    //---------------------------------------------------------------------------
    class TPartDescription
    {
    public:
    	TPartDescription(long code = 0,
    				 int year = 1960,
    				 UnicodeString make  = L"Unknown",
    				 UnicodeString model = L"Unknown",
    				 UnicodeString type  = L"Miscellaneous",
    				 UnicodeString desc  = L"Anything",
    				 double uPrice = 0.00);
    	~TPartDescription();
    public:
    	long PartNumber;
    	int CarYear;
    	UnicodeString Make;
    	UnicodeString Model;
    	UnicodeString Category;
    	UnicodeString PartName;
    	double UnitPrice;
    };
    //---------------------------------------------------------------------------
    #endif
  6. Access the PartDescription.cpp source file and change it class as follows:
    //---------------------------------------------------------------------------
    #pragma hdrstop
    
    #include "PartDescription.h"
    
    //---------------------------------------------------------------------------
    
    #pragma package(smart_init)
    
    //---------------------------------------------------------------------------
    __fastcall TPartDescription::TPartDescription(long code,
    				 	     int year,
    				 	     UnicodeString make,
    				 	     UnicodeString model,
    				 	     UnicodeString type,
    				 	     UnicodeString desc,
    				 	     double uPrice)
    {
    	PartNumber = code;
    	CarYear = year;
    	Make = make;
    	Model = model;
    	Category = type;
    	PartName = desc;
    	UnitPrice = uPrice;
    }
    //---------------------------------------------------------------------------
    __fastcall TPartDescription::~TPartDescription()
    {
    
    }
    //---------------------------------------------------------------------------
  7. On the main menu, click File -> New -> Other...
  8. In the right list of the New Items dialog box, click Unit and click OK
  9. To save the unit, on the Standard toolbar, click the Save All button Save All
  10. Set the name to PartSelected
  11. Click Save
  12. Change the header file as follows:
    //---------------------------------------------------------------------------
    
    #ifndef PartSelectedH
    #define PartSelectedH
    
    #include <vcl.h>
    //---------------------------------------------------------------------------
    class TPartSelected
    {
    public:
    	__fastcall TPartSelected(long code = 0,
    				 UnicodeString desc = L"Unknown",
    				 double uPrice = 0.00);
    	__fastcall ~TPartSelected();
    
    	long PartNumber;
    	UnicodeString PartName;
    	double UnitPrice;
    };
    //---------------------------------------------------------------------------
    #endif
  13. Access the source file and change it as follows:
    //---------------------------------------------------------------------------
    
    #pragma hdrstop
    
    #include "PartSelected.h"
    
    //---------------------------------------------------------------------------
    
    #pragma package(smart_init)
    
    __fastcall TPartSelected::TPartSelected(long code,
    					UnicodeString desc,
    					double uPrice)
    {
    	PartNumber = code;
    	PartName = desc;
    	UnitPrice = uPrice;
    }
    //---------------------------------------------------------------------------
    __fastcall TPartSelected::~TPartSelected()
    {
    }
    //---------------------------------------------------------------------------
  14. Display the form
  15. On the main menu, click File -> Use Unit...
  16. In the list, click one of the items
  17. Press and hold Shift
  18. Click the other items
  19. Release Shift
  20. Make sure the Header option is selected and click OK
  21. Under the Code Editor, click Inventory.h to access the header file
  22. Declare a private TList pointer named ListOfParts
    private:	// User declarations
    	TList * ListOfParts;
    public:		// User declarations
    	__fastcall TfrmInventory(TComponent* Owner);
    };
    //---------------------------------------------------------------------------
    extern PACKAGE TfrmInventory *frmInventory;
    //---------------------------------------------------------------------------
    #endif
  23. Click the Inventory.cpp tab and change the OnLoad event as follows:
    //---------------------------------------------------------------------------
    void __fastcall TfrmInventory::FormCreate(TObject *Sender)
    {
    	TDateTime Today = Date();
    	unsigned short Year, Month, Day;
    
    	Today.DecodeDate(&Year, &Month, &Day);
    
    	for (int i = Year; i >= 1960; i--)
    		cbxYears->Items->Add(i);
    
    	grdAvailableParts->ColWidths[0] = 60;
    	grdAvailableParts->ColWidths[1] = 260;
    	grdAvailableParts->ColWidths[2] = 70;
    
    	grdAvailableParts->Cells[0][0]  = L"Item #";
    	grdAvailableParts->Cells[1][0]  = L"Item Name";
    	grdAvailableParts->Cells[2][0]  = L"Unit Price";
    
    	ListOfParts = new TList;
    	TPartDescription * part = NULL;
    
    	part = new TPartDescription(447093, 2002, L"Ford",
    				L"Escort SE L4 2.0", L"Engine Electrical",
    				L"Alternator 75amp  Remanufactured; w/ 75 Amp",
    				205.05);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(203815, 2006, L"Dodge",
    				L"Caravan SE L4 2.4", L"Cooling System",
    				L"Radiator Cap", 6.65);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(293047, 2000, L"Toyota",
    				L"RAV4 2WD/4-DOOR", L"Cooling System",
    				L"Thermostat Gasket", 4.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(990468, 2002, L"Honda",
    				L"Civic 1.7 EX 4DR", L"Exhaust",
    			L"Bolt & Spring Kit (Manifold outlet, Muffler Inlet)",
    				85.75);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(304158, 1996, L"Buick",
    				L"Regal Custom V6 3.8", L"Fuel Injection",
    				L"Fuel Injector", 82.75);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(807245, 2004, L"Acura",
    				L"MDX 3.5 4WD", L"Driveshaft & Axle",
    			L"CV Boot Clamp 7 x 750mm; 1 Large + 1 Small Clamp",
    				1.60);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(203485, 2001, L"Ford",
    			L"Taurus LX V6 3.0", L"Fuel Injection",
    			L"Oxygen Sensor OE Style 4Wire; Front; 2 Required",
    			52.65);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(248759, 1999, L"Jeep",
    					L"Wrangler Sahara", L"Air Intake",
    					L"Air Filter AirSoft Panel", 7.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(202848, 1998, L"Honda",
    					L"Accord 2.3 LX 4DR", L"Air Intake",
    					L"Air Filter", 12.55);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(932759, 2006, L"Kia",
    				L"Rio 1.6DOHC16V 4-DR", L"Cooling System",
    				L"Thermostat", 14.45);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(304975, 2000, L"Honda",
    				L"Civic 1.6 EX 4DR", L"Suspension",
    				L"Ball Joint; Front Lower; 2 per car", 40.55);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(208450, 2003, L"Chevrolet",
    				L"Monte Carlo LS V6 3.4", L"Fuel Injection",
    				L"Oxygen Sensor OE connector; Rear", 65.55);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(209480, 2002, L"Ford",
    				L"Focus SE DOHC L4 2.0", L"Steering",
    				L"Steering Rack Remanufactured", 170.85);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(203495, 2004, L"Honda",
    				L"Civic 1.7 EX 4DR", L"Climate Control",
    				L"A/C Clutch; OE compressor = Sanden", 184.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(203480, 2007, L"Toyota",
    					L"Corolla", L"Air Intake",
    					L"Air Filter", 12.65);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(109379, 2005, L"Volvo",
    			L"S40 2.5L T5 AWD", L"Fuel Delivery",
    			L"Fuel Filter; Early Design; Outer Diameter = 55mm",
    			30.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(935794, 2002, L"Ford",
    				L"Escape XLS 4WD", L"Brake",
    				L"Brake Caliper Remanufactured; Front Right",
    				65.55);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(203485, 2006, L"BMW",
    					L"325i", L"Climate Control",
    					L"AC High Pressure Side Switch",
    					49.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(204875, 1996, L"Chevrolet",
    				L"Monte Carlo Z34 V6 3.4", L"Fuel Delivery",
    				L"Fuel Filter", 8.05);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(937485, 2007, L"Toyota",
    				L"Camry V6", L"Air Intake", L"Air Filter", 12.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(294759, 2001, L"Ford",
    					L"Escape XLT 4WD", L"Air Intake",
    					L"Air Filter Panel", 7.25);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(297495, 2003, L"Honda",
    			L"Civic 1.7 EX 4DR", L"Brake",
    			L"Brake Caliper Reman; w/ ProAct Pads; Front Right",
    			82.55);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(794735, 2006, L"BMW",
    				L"325i", L"Climate Control",
    				L"Cabin Air/Pollen Filter; With Activated Carbon",
    				28.05);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(937485, 2007, L"Toyota",
    				L"Corolla", L"Body Electrical",
    				L"Halogen  SilverStar; 12V 65W; inner-high beam",
    				22.85);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(492745, 2005, L"Ford",
    					L"Focus ZX3 L4 2.0", L"Air Intake",
    					L"Fuel Injection Perf Kit", 342.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(937005, 2004, L"Acura",
    		L"MDX 3.5 4WD", L"Driveshaft & Axle",
    		L"CV Boot Clamp 7 x 750mm; For Large End of Boot; inner boot",
    		1.60);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(293749, 2004, L"Acura",
    					L"MDX 3.5 4WD", L"Driveshaft & Axle",
    					L"Axle Nut 24mm x 1;5; rear ",
    					2.35);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(920495, 2006, L"BMW",
    					L"325i", L"Climate Control",
    					L"Adjustable Telescoping Mirror", 7.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(204075, 2004, L"Acura",
    					L"MDX 3.5 4WD", L"Driveshaft & Axle",
    					L"Wheel Bearing; Rear; 1 per wheel",
    					70.15);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(979304, 2000, L"Toyota",
    					L"RAV4 2WD/4-DOOR", L"Cooling System",
    					L"Thermostat Housing", 20.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(300456, 2004, L"Acura",
    				L"MDX 3.5 4WD", L"Driveshaft & Axle",
    				L"Wheel Bearing; Front; 1 per wheel", 66.65);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(404860, 2001, L"Ford",
    					L"Taurus LX V6 3.0", L"Suspension",
    					L"Shock Absorber GR2; Rear; Wagon only",
    					39.40);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(585688, 2007, L"Buick",
    					L"Lacrosse CXS V6 3.6", L"Brake",
    					L"Climate Control", 10.65);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(739759, 2001, L"Ford",
    			L"Taurus LX V6 3.0", L"Suspension",
    			L"Shock Absorber GasaJust; Rear; Wagon only", 30.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(927495, 2005, L"Volvo",
    			L"S40 2.5L T5 AWD", L"Engine Mechanical",
    			L"Timing Belt Idler Pulley Original Equipment INA",
    			65.55);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(979374, 2000, L"Toyota",
    					L"RAV4 2WD/4-DOOR", L"Cooling System",
    					L"Thermostat Gasket", 4.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(542347, 2007, L"Buick",
    			L"Lacrosse CXS V6 3.6", L"Brake",
    			L"Brake Pad Set ProACT Ceramic w/Shims; Front", 80.05);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(683064, 2000, L"Toyota",
    					L"RAV4 2WD/4-DOOR", L"Cooling System",
    					L"Radiator Hose; Upper", 103.75);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(248759, 1999, L"Jeep",
    					L"Wrangler Sahara", L"Air Intake",
    					L"Air Filter", 50.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(973974, 2007, L"Toyota",
    			L"Corolla", L"Air Intake",
    			L"Air Mass Meter; W/o Housing; Meter/sensor only",
    			134.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(285800, 2001, L"Ford",
    			L"Escape XLT 4WD", L"Transmission", L"AT Filter", 34.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(207495, 2007, L"Toyota",
    			L"Corolla", L"Body Electrical",
    			L"Headlight Bulb; 12V 65W; inner-high beam", 9.35);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(566676, 2000, L"Toyota",
    					L"RAV4 2WD/4-DOOR", L"Cooling System",
    					L"Auxiliary Fan Switch", 42.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(304950, 2007, L"Toyota",
    					L"Corolla", L"Body Electrical",
    					L"Headlight Bulb; 12V 51W; outer", 7.85);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(797394, 2000, L"Toyota",
    					L"RAV4 2WD/4-DOOR", L"Cooling System",
    					L"Water Flange Gasket", 0.85);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(910203, 2007, L"Buick",
    				L"Lacrosse CXS V6 3.6", L"Suspension",
    				L"Strut Mount Inc; Sleeve; Rear Right", 80.85);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(790794, 2000, L"Toyota",
    					L"RAV4 2WD/4-DOOR", L"Cooling System",
    					L"Radiator Hose; Lower", 9.45);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(970394, 2007, L"Buick",
    				L"Lacrosse CXS V6 3.6", L"Suspension",
    				L"Coil Spring Insulator; Front Lower", 14.55);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(290840, 2005, L"Volvo",
    		L"S40 2.5L T5 AWD", L"Engine Mechanical",
    		L"Rod Bearing Set 1 per Rod; Standard; Reqs. 5-per Engine",
    		26.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(209704, 2007, L"Toyota",
    					L"Corolla", L"Body Electrical",
    					L"Wiper Blade Excel+; Front Right", 7.25);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(200368, 2000, L"Toyota",
    				L"RAV4 2WD/4-DOOR", L"Cooling System",
    				L"Radiator Drain Plug incl; gasket", 3.15);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(200970, 2005, L"Volvo",
    			L"S40 2.5L T5 AWD", L"Engine Mechanical",
    			L"Reference Sensor; Flywheel Engine Speed", 62.05);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(542347, 2007, L"Buick",
    					L"Lacrosse CXS V6 3.6", L"Air Intake",
    					L"Air Filter", 50.25);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(927045, 2001, L"Ford",
    					L"Escape XLT 4WD", L"Air Intake",
    					L"Air Filter", 62.95);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(990659, 2000, L"Toyota",
    					L"RAV4 2WD/4-DOOR", L"Cooling System",
    					L"Radiator OE Plastic tank", 136.85);
    	ListOfParts->Add(part);
    
    	part = new TPartDescription(440574, 2007, L"Buick",
    				L"Lacrosse CXS V6 3.6", L"Suspension",
    				L"Strut Mount Inc; Sleeve; Rear Left", 80.80);
    }
    //---------------------------------------------------------------------------
  24. Return to the form and double-click the Year combo box
  25. To display the list of car makes when the user selects a year, implement the event as follows:
    //---------------------------------------------------------------------------
    void __fastcall TfrmInventory::cbxYearsChange(TObject *Sender)
    {
    	// Empty all combo boxes
    	cbxMakes->Text = "";
    	cbxMakes->Items->Clear();
    	cbxModels->Text = "";
    	cbxModels->Items->Clear();
    	cbxCategories->Text = "";
    	cbxCategories->Items->Clear();
    
    	// Get to each record in the list of parts
    	for(int i = 0; i < ListOfParts->Count; i++)
    	{
    		// Get a reference to the record that is currently being checked
    		TPartDescription * part =
    			reinterpret_cast<TPartDescription *>(ListOfParts->Items[i]);
    
    		// If year of the record is the same as the year in the combo box,
    		// then show its corresponding makes
    		if( part->CarYear == cbxYears->Text.ToInt() )
    			if( cbxMakes->Items->IndexOf(part->Make) <= -1)
    				cbxMakes->Items->Add(part->Make);
    	}
    }
    //---------------------------------------------------------------------------
  26. Return to the form and double-click the Make combo box
  27. To display the list of car models when the user has selected a year and a make, implement the event as follows:
    //---------------------------------------------------------------------------
    void __fastcall TfrmInventory::cbxMakesChange(TObject *Sender)
    {
        cbxModels->Text = "";
        cbxModels->Items->Clear();
        cbxCategories->Text = "";
        cbxCategories->Items->Clear();
    
        for(int i = 0; i < ListOfParts->Count; i++)
        {
    	TPartDescription * part =
    		reinterpret_cast<TPartDescription *>(ListOfParts->Items[i]);
    
    	if( (part->CarYear == cbxYears->Text.ToInt() ) &&
    	    (part->Make == cbxMakes->Text))
    		if( cbxModels->Items->IndexOf(part->Model) <= -1)
    			cbxModels->Items->Add(part->Model);
        }
    }
    //---------------------------------------------------------------------------
  28. Return to the form and double-click the Model combo box
  29. To display the list of categories after the user has selected the year, the make, and the model, implement the event as follows:
    //---------------------------------------------------------------------------
    void __fastcall TfrmInventory::cbxModelsChange(TObject *Sender)
    {
        for(int i = 0; i < ListOfParts->Count; i++)
        {
    	TPartDescription * part =
    		reinterpret_cast<TPartDescription *>(ListOfParts->Items[i]);
    
    	if( (part->CarYear == cbxYears->Text.ToInt() ) &&
    	    (part->Make == cbxMakes->Text) &&
    	    (part->Model == cbxModels->Text) )
    		if (cbxCategories->Items->IndexOf(part->Category) <= -1)
    			cbxCategories->Items->Add(part->Category);
        }
    }
    //---------------------------------------------------------------------------
  30. Return to the form and double-click the Category combo box
  31. To display the list of available parts, implement the event and define a new method  as follows:
    //---------------------------------------------------------------------------
    void __fastcall TfrmInventory::cbxCategoriesChange(TObject *Sender)
    {
        // This list will hold some items based on the selection
        TList * SelectedParts = new TList();
    
        // Check each record in the list of parts
        for(int i = 0; i < ListOfParts->Count; i++)
        {
    	// Get a reference to the part that is being checked
    	TPartDescription * part =
    		reinterpret_cast<TPartDescription *>(ListOfParts->Items[i]);
    
            // If/When you find a record that matches
    	// the values of the combo boxes . . .
    	if( (part->CarYear == cbxYears->Text.ToInt() ) &&
    		(part->Make == cbxMakes->Text) &&
    		(part->Model == cbxModels->Text) &&
    		(part->Category == cbxCategories->Text))
    	{
    		// . . . get the values from that part and create a selected part
    		TPartSelected *selected = new TPartSelected(part->PartNumber,
    							 part->PartName,
    							 part->UnitPrice);
    		SelectedParts->Add(selected);
    	}
        }
    
        grdAvailableParts->RowCount = SelectedParts->Count + 1;
    
        if( SelectedParts->Count > 0 )
        {
    	for(int i = 1; i <= SelectedParts->Count; i++)
    	{
    	    TPartSelected * item = 
    		reinterpret_cast<TPartSelected *>(SelectedParts->Items[i - 1]);
    
    	    grdAvailableParts->Cells[0][i] = item->PartNumber;
    	    grdAvailableParts->Cells[1][i] = item->PartName;
    	    grdAvailableParts->Cells[2][i] = item->UnitPrice;
    	}
        }
    }
    //---------------------------------------------------------------------------
  32. Save all

The Styles of a Combo Box

There are three styles of combo boxes, although all allow the user to make only one selection. These styles are controlled by the TComboBoxStyle enumeration:

enum TComboBoxStyle{
	csDropDown,
	csSimple,
	csDropDownList,
	csOwnerDrawFixed,
	csOwnerDrawVariable
};

The TComboBoxStyle enumeration controls the Style property:

__property Stdctrls::TComboBoxStyle Style = {read=FStyle,write=SetStyle};

A combo box can be configured to allow the user to add items to the list. In this case, if the user does not find the desired item in the list, he can type a new value:

Combo Box

To provide this ability, set the Style to csDropDown, which is the default style. If you set the Style to csDropDownList, the user cannot enter a new item in the list but can still select one from the control:

Simple Style Combo Box Simple Style Combo Box

A combo box with the csSimple Style permanently displays a combination of an edit box and a list box:

Combo Box

 

Practical LearningPractical Learning: Applying a Style to a Combo Box

  1. On the form, click the Make combo box
  2. In the Object Inspector, click Style, then click the arrow of its combo box and select csDropDownList
  3. On the form, click the Model combo box
  4. Press and hold Shift
  5. Click the Category combo box
  6. Release Shift
  7. In the Object Inspector, click Style, then click the arrow of its combo box and select csDropDownList
  8. Save all
  9. To execute the application to test it, on the Standard toolbar, click the Run button Run
     
    College Park Auto Parts
     
    College Park Auto Parts
     
    College Park Auto Parts
  10. After using it, close the form and return to your programming environment

The Number of Dropped Down Items

If the combo box has a style other than csSimple, there is typically a fixed number of items that display when the user clicks the controlís arrow. You can control the number of items that displays using the DropDownCount property:

__property int DropDownCount = {read=FDropDownCount,write=SetDropDownCount};

By default, this is set to 8. If the list contains a number of items less than the DropdownCount integer value, all of the items would display fine. If the list contains more than the DropDownCount number of items, when the user clicks the arrow, a scroll box would appear. The control would display DropDownCount number of items. To reveal more, the user would have to scroll in the list. The user can scroll in the list box and select an item. After the selection, the control would still display the list.

The other two styles, csOwnerDrawFixed and csOwnerDrawVariable, are typically used to display varying objects such as pictures or colors.

The Index of an Item

The text that displays on a non-drawn combo box is a UnicodeString object. If you want the combo box to display a certain string, use the Text property. At design time, you can set this only if the controlís Style is csDropDown or csSimple. At run time, you can set the text that would display in the combo box at startup using the ItemIndex property. This property represents the ordinal integer item of the combo box. The items are counted from 0, then 1, and so on. The ItemIndex of each item is set depending on the value to the Sorted property. If the list is not sorted, the first item entered in the list has an ItemIndex value of 0. If the list gets sorted, the first item in ascending order has an ItemIndex property set at 0. You can therefore use this property to control what item to display in the list:

//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
	cbxColors->ItemIndex = 0;
}
//---------------------------------------------------------------------------

You can also use the ItemIndex property to find out what item is selected at a given time.

 
 
   
 

Home Copyright © 2010-2011 FunctionX, Inc.