Home

Check-Based Controls

 

Check Boxes

 

Introduction

A check box is a Windows control that allows the user to set or change the value of an item as true or false. Although it can appear by itself, a check box sometimes comes in a group with others, allowing the user to select as many choices as are available. Depending on the application, a little square £ appears. The user makes a selection by clicking in the square which toggles a check mark T. Toggling means that if the square were empty £, after clicking it, a check mark would appear in it T. Otherwise, the check mark would be removed. Like a radio button, a check box is usually accompanied by a label to indicate what the check control is used for.

From the user’s standpoint, a check box is selected when its check mark is set; and the item is not selected when its square is empty. From the developer standpoint, a check mark has two (Boolean) values: true or false (or TRUE or FALSE, or True or False). When a check mark is selected, its value is true. Otherwise, its value is false.

A check mark is a special button and can be programmed as a regular control. Depending on the application’s needs, you can display or hide it, enable or disable it as necessary. You can adjust the control’s behavior depending on other controls on the same form, the same application, or external factors.

Check boxes provide “non-exclusive” choice, which means that each check box can behave as independent as needed with regards to the other check boxes of the same container. If you are creating just one check box, you can place it where you want on the form. If you are creating more than one check box that are addressing the same issue, you should include them in a rectangular container so their belonging to the same group would be obvious to the user. The group can be hosted by a GroupBox, a bevel, a RadioGroup, or a Panel controls. If you place the controls in a Bevel or a RadioGroup, since these two are true containers for other controls, you will not be able to move all controls as one object during design.

Practical Learning Practical Learning: Introducing Check Boxes

  1. Start a new project with its default form
  2. Save it in a new folder named FastFood1
  3. Save the unit as Exercise and save the project as FastFood
  4. Open Image Editor. Design a 32 x 32 and 16 x 16 icon as follows:
     
  5. Save it as FastFood in the folder of the current project
  6. Create a new 16 x 16 size bitmap and design it as follows:
     
  7. Save it as Ingredients in the folder of the current project
  8. In the project options (Project -> Options), access the Application tab. Set the Title to Fast Food Corner and sect the icon to the above FastFood icon
  9. Change the form’s following properties:
    BorderStyle: bsDialog
    Caption: Fast Food Restaurant – Customer Menu
    Name: frmMain
    Position: poScreenCenter
  10. Design the dialog box as follows:
     
    Control Name Caption Other Properties
    GroupBox   Bread  
    RadioButton rdoBun B&un Alignment: taLeftJustify
    RadioButton rdoRoll &Roll Alignment: taLeftJustify
    Checked: true
    Group Box   Meat  
    Radio Button rdoBeefPatty Bee&f Patty Alignment: taLeftJustify
    Checked: true
    Radio Button rdoGrilledChicken &Grilled Chicken Alignment: taLeftJustify
    Radio Button rdoChickedBreast C&hicken Breast Alignment: taLeftJustify
    GroupBox   Ingredients  
  11. Save All

Characteristics of Check Boxes

If you are planning to have just one check box, from the Standard section of the Tool Palette, click the CheckBox control and click on the desired section of the form or container. If you want to use more than one check box, you should first place a group control on your form, then add the desired CheckBox controls.

The most obvious property of the check box is its state as being checked or not. By default, a check box is not checked (it is empty). At design time, you can make sure that a check box appears checked or not by changing the Boolean value of the Checked property in the Object Inspector. When you set this property, it would be updated automatically on the form. You or the user can also control this property at runtime. To change the Checked property programmatically, simply assign a true or false value to the Checked property. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
	CheckBox1->Checked = True;
}
//---------------------------------------------------------------------------

When a check box is clicked, its Checked property has a value of true. Otherwise, the value is false. Since the Checked property is a Boolean value, you can toggle its state based on an intermediary action from the program, the user, or the computer:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
	CheckBox1->Checked = !CheckBox1->Checked;
}
//---------------------------------------------------------------------------

Another important property of a check box is its title, which is controlled by the Caption property. This can easily be set at design or runtime.

The position of the caption is controlled by the Alignment property. By default, the control's caption is aligned to the right side of the check box:

Right Aligned Left Aligned

Figure 82:  Figure 83: 

To change the caption alignment of a check box, use the Alignment property of the Object Inspector. The values are taRightJustify for the right alignment and the taLeftJustify.

Fundamentally, a check box can have only one of two states: checked or unchecked. When a check box’ Checked property is dependent of other controls or actions, sometimes, you cannot categorically set it to Checked or not Checked. Imagine that, in a certain company, for an employee to qualify for stock options, she must be have a full-time status and must have been in the company for at least two years. If an (important) employee fulfills one of these requirements but not the other requirements, you can gray out the Stock Options check box. since the control would not be completely checked, you can show it as half checked:

This property is controlled by the AllowGrayed property. In the Object Inspector, change the (Boolean) AllowGrayed property of the desired check box to true or false (the default). Programmatically, to set this property, assign it a true value (because otherwise the false value is set by default).

At design time or when the user is interacting with your application, you can control the display of a check box using one of three states. Unlike being checked or unchecked, like the AllowGrayed property, you can use an intermediary state that would help you and/or the user know that the control’s condition cannot be definitely decided. This is set using the State property. This property, based on the TCheckBoxState enumerator, allows you to set a check box as unchecked (the default) by assigning the cbUnchecked value. To definitely check it, set this property to cbChecked. As a 3rd alternative, you can assign it a cbGrayed value.

Practical Learning Practical Learning: Creating Check Boxes

  1. On the Standard toolbar, click the New button . In the New Items dialog box, click Dialogs and double-click Standard Dialog (Vertical)
  2. Save it as Ingredients
  3. Change its Name to dlgIngredients
  4. Change its Caption to Ingredients Selection
  5. Design the dialog box as follows:
     
    Control Name Caption Other Properties
    CheckBox chkLettuce &Lettuce Alignment: taLeftJustify
    Checked: true
    CheckBox chkOnion &Onion Alignment: taLeftJustify
    CheckBox chkTomato &Tomato Alignment: taLeftJustify
    Checked: true
    CheckBox chkPickles &Pickles Alignment: taLeftJustify
  6. Display the main form (View -> Forms… -> frmMain -> OK)
  7. Complete its design as follows:
     
    Control Name Caption Other Properties
    CheckBox chkRegulars &Regulars Alignment: taLeftJustify
    AllowGrayed: true
    CheckBox chkSweetener &Sweetener Alignment: taLeftJustify
    Checked: true
    CheckBox chkCheese Ch&eese Alignment: taLeftJustify
    CheckBox chkBacon B&acon Alignment: taLeftJustify
    GroupBox   Options  
    BitBtn btnIngredients &Ingredients Glyph: Ingredients
    RadioButton rdoMayonnaise &Mayonnaise Alignment: taLeftJustify
    Checked: true
    RadioButton rdoKetchup &Ketchup Alignment: taLeftJustify
    RadioButton chkMustard Mus&tard Alignment: taLeftJustify
    Bevel     Shape: bsFrame
    BitBtn     Kind: bkClose
    Label   Total Price:  
    Edit edtTotalPrice $2.35  
  8. On the main form, double-click the Ingredients button and implement its OnClick() event as follows:
     
    //---------------------------------------------------------------------------
    #include <vcl.h>
    #pragma hdrstop
    
    #include "Exercise.h"
    #include "Ingredients.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    #pragma resource "*.dfm"
    TfrmMain *frmMain;
    //---------------------------------------------------------------------------
    __fastcall TfrmMain::TfrmMain(TComponent* Owner)
    	: TForm(Owner)
    {
    }
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::btnIngredientsClick(TObject *Sender)
    {
    	dlgIngredients->ShowModal();
    }
    //---------------------------------------------------------------------------
  9. Test the application. Close it and return to Borland C++ Builder
  10. Save All

Check Box Methods and Events

The check box control has only its constructor and its destructor as methods. The constructor allows you to dynamically create the control. To do this, use the new operator to assign a TCheckBox object to the named instance of the control. You must also specify what control owns the check box. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
	TCheckBox* Checker = new TCheckBox(Form1);
	Checker->Parent = Form1;
}
//---------------------------------------------------------------------------

If the check box will be hosted by a container other than the form, specify this as the parent:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
	TCheckBox* Checker = new TCheckBox(Form1);
	Checker->Parent = GroupBox1;
}
//---------------------------------------------------------------------------

If you do not have or cannot get a container at design time, you can also dynamically create one that would host the dynamic check boxes. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
	TGroupBox* Group = new TGroupBox(Form1);
	Group->Parent = Form1;
	Group->Left = 16;
	Group->Top = 32;
	Group->Caption = "Preferred Sports";

	TCheckBox* chkFootball = new TCheckBox(Form1);
	chkFootball->Parent = Group;
	chkFootball->Left = 16;
	chkFootball->Top = 16;
	chkFootball->Alignment = taRightJustify;
	chkFootball->Caption = "Football";
	chkFootball->Checked = True;

	TCheckBox* chkHandball = new TCheckBox(Form1);
	chkHandball->Parent = Group;
	chkHandball->Left = 16;
	chkHandball->Top = 36;
	chkHandball->Caption = "Handball";
}
//---------------------------------------------------------------------------

If you want to know the alignment applied on a check box, call the GetControlsAlignment() method. Its syntax is:

TAlignment __fastcall GetControlsAlignment(void);

Most of the other methods a check box uses derive from its ancestors the TControl and the TWinControl classes.

As far as Microsoft Windows is concerned, a check box is just a modified button. This allows it to use the common characteristics of command buttons and radio controls. Based on this, when the user clicks a check box, an OnClick() event fires. All the other events derive from its ancestors the TControl and the TWinControl classes.

Practical Learning Practical Learning: Implementing Check Boxes

  1. If the user completely removes the check mark on the Sweetener check box, this suggests that the customer does not want this item on the sandwich. Consequently, the radio buttons in the Options group should be disabled. When the user clicks a check box, whether the control was already checked or not, the OnClick() event fires. Therefore, in this case, the first thing you should do it to check the state of the check button and then implement a behavior accordingly.
    Display the main form and double-click the Sweetener check control
  2. Implement its OnClick event as follows:
     
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::chkSweetenerClick(TObject *Sender)
    {
    	// If the sweetener check box is not checked
    	if( chkSweetener->Checked == False )
    	{
    		// Disable the Options radio buttons
    		rdoMayonnaise->Enabled = False;
    		rdoKetchup->Enabled = False;
    		rdoMustard->Enabled = False;
    	}
    	else
    	{
    		// Otherwise, enable the Options radio buttons
    		rdoMayonnaise->Enabled = True;
    		rdoKetchup->Enabled = True;
    		rdoMustard->Enabled = True;
    	}
    }
    //---------------------------------------------------------------------------
  3. To keep track of the user’s selection of ingredients, we will use four global variables that each represents a check box from the Ingredients dialog.
    In the header file of the main form, declare four private Boolean variables as follows:
     
    private:
    	Boolean bLettuce, bOnion, bTomato, bPickles;
  4. In the constructor of the main form, initialize the variables with a false value each:
     
    //---------------------------------------------------------------------------
    __fastcall TfrmMain::TfrmMain(TComponent* Owner)
    	: TForm(Owner)
    {
    	bLettuce = False;
    	bOnion = False;
    	bTomato = False;
    	bPickles = False;
    }
    //---------------------------------------------------------------------------
  5. When the user clicks the Regulars check box, we will update the global variables appropriately.
    On the form, double-click the Regulars check box and implement its OnClick() event as follows:
     
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::chkRegularsClick(TObject *Sender)
    {
    	// If the Regulars check box is completely unchecked
    	if( chkRegulars->State == cbUnchecked )
    	{
    		// Set the global Boolean variables to false each
    		bLettuce = False;
    		bOnion = False;
    		bTomato = False;
    		bPickles = False;
    	}
    	// If the Regulars check box is completely checked
    	else if( chkRegulars->State == cbChecked )
    	{
    		// Set the global Boolean variables to true each
    		bLettuce = True;
    		bOnion = True;
    		bTomato = True;
    		bPickles = True;
    	}
    	// Otherwise, refer to the state of the check boxes
    	// from the Ingredients dialog box. Whatever they are
    	else
    	{
    		bLettuce = dlgIngredients->chkLettuce->Checked;
    		bOnion = dlgIngredients->chkOnion->Checked;
    		bTomato = dlgIngredients->chkTomato->Checked;
    		bPickles = dlgIngredients->chkPickles->Checked;
    	}
    }
    //---------------------------------------------------------------------------
  6. When the Regulars check box is not checked at all, no basic ingredient is selected. When this control is checked, all ingredients will be added to the sandwich. If at least one ingredient is selected and at least one ingredient is not selected, the Regulars check box should appear grayed.
    When the user clicks the Ingredients button, we will display the Ingredients Selection dialog box and allow the user to select the ingredients. If the user clicks OK to dismiss the dialog box, we will apply the above scenario.
    On the form, double-click the Ingredients button and change its OnClick event as follows:
     
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::btnIngredientsClick(TObject *Sender)
    {
    	// Before displaying the dialog box, synchronize its
    	// check boxes with the global variables
    	dlgIngredients->chkLettuce->Checked = bLettuce;
    	dlgIngredients->chkOnion->Checked = bOnion;
    	dlgIngredients->chkTomato->Checked = bTomato;
    	dlgIngredients->chkPickles->Checked = bPickles;
    
    	// Call the Ingregients Selection dialog box for the user
    	// If the user clicked OK when closing the dialog box,
    	dlgIngredients->ShowModal();
    
    	if( dlgIngredients->ModalResult == mrOk )
    	{
    		// If the user clicks OK, 
    		// update the global values of the check boxes
    		bLettuce = dlgIngredients->chkLettuce->Checked;
    		bOnion = dlgIngredients->chkOnion->Checked;
    		bTomato = dlgIngredients->chkTomato->Checked;
    		bPickles = dlgIngredients->chkPickles->Checked;
    
    		// if no check box is checked
    		if( (bLettuce == False) &&
    		    (bOnion == False) &&
    		    (bTomato == False) &&
    		    (bPickles == False) )
    		    // then uncheck this one
    		    chkRegulars->State = cbUnchecked;
    		// if all check boxes are checked
    		else if( (bLettuce == True) &&
    			 (bOnion == True) &&
    			 (bTomato == True) &&
    			 (bPickles == True) )
    			chkRegulars->State = cbChecked; // then check this one
    		else // if at least one check box is 
    		     // checked and at one is unchecked
    		     // then set this one as indeterminate
    		     chkRegulars->State = cbGrayed;
    	}
    	// If the user clicked Cancel, don't do nothing
    }
    //---------------------------------------------------------------------------
  7. Now we can calculate the price of the sandwich.
    In the header file of the main form, declare a private member function of type void __fastcall named EvaluatePrice

  8. Implement the method as follows:
     
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::EvaluatePrice()
    {
    	//TODO: Add your source code here
    	double PriceBread, PriceMeat,
    	PriceCheese, PriceBacon, TotalPrice;
    
    	// The price of bread is $0.85
    	PriceBread = 0.85;
    
    	// To get the price of the meat, find out what button
    	// is selected in the Meat group box
    	if( rdoBeefPatty->Checked == True )
    		// The beef patty is $1.50
    		PriceMeat = 1.50;
    	else if( rdoGrilledChicken->Checked == True ||
    		 rdoChickenBreast->Checked == True )
    		// Cheicken breast and grilled chicken are $1.80 each
    		PriceMeat = 1.80;
    	else // Just in case
    		PriceMeat = 0.00;
    
    	// There is no extra cost for the Regular ingredients
    	// and nothing to add for the sweetener
    
    	// On the other hand,
    	// if the customer wants cheese, $0.30 is added to the price
    	if( chkCheese->Checked == True )
    		PriceCheese = 0.30;
    	else // otherwise, the customer don't want no cheese
    		PriceCheese = 0.00;
    
    	// If the customer wants bacon, $0.45 is added to the price
    	if( chkBacon->Checked == True )
    		PriceBacon = 0.45;
    	else
    	PriceBacon = 0.00;
    
    	// Now, we can calculte the total price
    	TotalPrice = PriceBread + PriceMeat + PriceCheese + PriceBacon;
    	edtTotalPrice->Text = FloatToStrF(TotalPrice, ffCurrency, 8, 2);
    }
    //---------------------------------------------------------------------------
  9. To update the price and its display live whenever the user makes a new selection, double-click the following controls: Beef Patty, Grilled Chicken, Chicken Breast, Cheese, and Bacon
  10. In the body of each, simply call the above EvaluatePrice() method:
     
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::rdoBeefPattyClick(TObject *Sender)
    {
    	EvaluatePrice();
    }
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::rdoGrilledChickenClick(TObject *Sender)
    {
    	EvaluatePrice(); 
    }
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::rdoChickedBreastClick(TObject *Sender)
    {
    	EvaluatePrice();
    }
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::chkCheeseClick(TObject *Sender)
    {
    	EvaluatePrice();
    }
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::chkBaconClick(TObject *Sender)
    {
    	EvaluatePrice();
    }
    //---------------------------------------------------------------------------
  11. Test the application:
     
    The Fast Food Restaurant Application
  12. Close it and return to Borland C++ Builder
  13. Heighten the form and add the following controls to the top section

    The Fast Food Application Improvement 

     
    Control Name Caption/Text Other Properties
    Label   Processed By:  
    Edit edtClerk    
    Label   Order Date:  
    MaskEdit edtOrderDate   EditMask: !99/99/0000;1;_
  14. Save All

Checked List Boxes

 

Introduction

A Check List Box is a List Box whose items are each equipped with a check box:


Figure 89: The Project Options Dialog Box

A Check List Box combines the functionalities of the List Box and the Check Box controls. As a list box, it displays each of its items on a line. If there are too many items than the control can display, it would be equipped with a vertical scroll bar. As described for the list box, if at least one of the items is wider than the control's width, you can make the list box display a horizontal scroll bar.

To select an item in the list, the user can click the desired string. Unlike the regular list box, the user cannot select more than one string in the list. For this reason, if you desire a normal list of objects, use the regular List Box control. The most important and obvious characteristic of the Check List Box is that each item displays a check box on its left. This box allows the user to select or deselect each item. To select an item, the user must click its box and not its string, to indicate an explicit selection. This draws a check mark in the box. As described with the Check Box control, the user can deselect a string by removing the check mark. The check mark indicates that an item is selected and the absence of the check mark indicates the contrary. Like the Check Box control, you can allow the user to indicate a "half-checked" item. In this case, a check box can appear unchecked, checked, or grayed.

 

Practical Learning Practical Learning: Creating a Pizza Application

  1. 1. Start a new project with its default form
    2. Save the project in a new folder named Pizza1
    3. Save the unit as Main and the project as Pizza
    4. Design the form as follows:


    Control Name Caption Other Properties
    Form BorderStyle: bsDialogShowHint: true
    GroupBox Caption: Pizza Size 
    RadioButton rdoSmall Small Alignment: taLeftJustify
    RadioButton rdoMedium Meium Alignment: taLeftJustify
    RadioButton rdoLarge Large Alignment: taLeftJustify

    5. Save All

Characteristics of a Checked List Box

To provide a Check List Box, from the Additional tab of the Tool Palette, click the CheckListBox button and click the form or container that would host the control.

Like the regular List Box control, the items of a Check List Box object are AnsiString strings controlled by a TStrings list called Items. At design time, to create a list of items and add it to the control, open the String List Editor dialog box, add the necessary strings, and click OK. Of course, you can add the strings at run time, using the Items::Add() method.

After creating the list, each item appears with a flat check box to its left. If you want a 3-D check box, you can change the Boolean Flat property from its true default to a false value:

Flat = true Flat = false



When you create the list, the items are stored in the same order you entered them, if you want, you can rearrange them alphabetically or numerically. This can be done by setting the Boolean value of the Sorted property accordingly. As described for the list box, if you set it to true, the items of the Check List Box would be sorted. If you set it back to false, the items of the list box would not go back to the way they were but new items would be added at the end of the list.

If you provide a longer list than the control's height can display, it would have a vertical scroll bar. If just one or a few items are hidden by the scroll bar, you can heighten it if the form provides more space. Alternatively, you can also create the list in various columns. To do this, set the value of the Columns property to a number of your choice. Here is a Check List Box with two columns:



Normally, the number of columns should not exceed 5 or this would indicate that you may simply need more than one Check List Box control:

If at least one of the items is wider than the width of the control, you have various alternatives. You can display a horizontal scroll bar by calling the Win32 API SendMessage() function and specifying the LB_SETHORIZONTALEXTENT value as the message to send:

//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
	SendMessage(CheckListBox1->Handle, LB_SETHORIZONTALEXTENT, 140, 0);
}
//---------------------------------------------------------------------------

You can also resize the control to make it wider to accommodate the large item. After creating the list, sorted or not, each item has a positional index that allows you to access it. The array of this index can have a different name depending on why you want to access it. For example, the items are stored in an array called Header and each item can be accessed using the Header[Index] array. The Header index is used if you want an item to be distinct from the others. To do this, at run time, access that item Header index and set its Header Boolean property to true. To distinguish the header item from the others, it uses a different text color and it does not display a check box. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
	CheckListBox1->Header[2] = True;
}
//---------------------------------------------------------------------------

In the same way, you can make more than one item appear as Header. The Header item displays a color represented by the HeaderBackgroundColor property. The text of the Header item displays in a color known as the HeaderColor property. You can set these values to any valid color you want.

Also, the items are stored in an array called Checked. The first, top, item has an index of 0 and can be accessed with Checked[0]. The second item has an index of 1 and can be accessed with Checked[0], etc. As stated already, to select an item, the user clicks its check box. To find out if an item has been checked, access its Checked index and check whether it is true or false. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::CheckListBox1Click(TObject *Sender)
{
	if( CheckListBox1->Checked[1] == True )
		ShowMessage("Welcome to Montgomery County!");
}
//---------------------------------------------------------------------------

To increase the options of the Check List Box, you can let the user "half-Select" an item or indicate when an item is not completely selected and not completely deselected. Such an item is referred to as grayed. To allow this, you must set the AllowGrayed Boolean property to true. If a Check List Box control has this property on, to check the appearance of a check mark or absence of it on an item, use the State property. The value of this property is an enumeration type defined as follows:

enum TCheckBoxState {cbUnchecked, cbChecked, cbGrayed};
  • If an item is checked, its State has a value of cbUncheckedq If an item is clearly checked, its State has a value of cbCheckedq If an item is undecided, that is, if it is grayed, its State has a value of cbGrayed

The check mark appearance of the items of a Check List Box control are stored in an array called State. To find out the check mark or lack of it of an item, call the State property and specify the index of the desired item. The following checks whether a check mark appears on the 5th item of the list:

//---------------------------------------------------------------------------
void __fastcall TForm1::CheckListBox1Click(TObject *Sender)
{
	if( CheckListBox1->State[4] == cbChecked )
		ShowMessage("The Bay Bridge is closed.\nYou can't get to Annapolis!!!");
}
//---------------------------------------------------------------------------

If for any reason you do not want the users to be able to select items, only to view the list, you can set the Enabled property of the control to false. On the other hand, if you want to disable only one or a few items, you can do that. The items of a Check List Box are stored in an array called ItemEnabled[Index]. To enable or disable an item, call this property and specify the index of the item you want to enable or disable. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
	CheckListBox1->ItemEnabled[2] = False;
	CheckListBox1->ItemEnabled[4] = False;
	CheckListBox1->ItemEnabled[5] = False;
}
//---------------------------------------------------------------------------

Practical Learning Practical Learning: Creating a Check List Box Application

  1. On the Tool Palette, click the Additional tab and click the CheckListBox button
  2. Click an empty area on the form
  3. While the CheckListBox control is still selected, on the Object Inspector, click the ellipsis button of the Items
  4. Create the list of items as follows:

    Figure 90: The String List Editor for a Check List Box

    5. Click OK
    6. Change the Name of the control to lstToppings
    7. Design the rest of the form as follows:

    Figure 91: The Pizza Application in Design

    Control Name Caption or Text Other Properties
    Label Toppings Selection 
    CheckListBox 
    GroupBox Topping Distribution 
    RadioButton rdoMixToppings Mix Toppings 
    RadioButton rdoHalfAndHalf Half and Half 
    RadioButton rdoThirdAnd2Thirds 1/3 and 2/3 
    RadioButton rdoThirdEach 1/3 Each 
    Label Pizza Price 
    Edit edtPizzaPrice 9.25 
    Label Price Toppings 
    Edit edtPriceToppings 0.00 
    Label Total Price 
    Edit edtTotalPrice 0.00 
    BitBtn Kind: bkClose

    8. Save All

Methods to Manage a Check List Box

A Check List Box control is based on the TCheckListBox class. Therefore, to programmatically create this control, you can use its constructor. Specify the control owner and its parent. All of the functionality of the Check List Box control is provided though its properties.

When the user clicks the check box of an item, the Check List Box fires an OnClickCheck event. You can use this event to take some action. The OnClickCheck event of a TNotifyEvent type and therefore specifies only the Sender of the event.

Practical Learning Practical Learning: Using Check List Box Events

  1. On the form, click the Check List Box to select it and, on the Object Inspector, click the Events tab
  2. Double-click the event side of the OnClickCheck field and implement it as follows:
    //---------------------------------------------------------------------------
    void __fastcall TForm1::lstToppingsClickCheck(TObject *Sender)
    {
    int Pepperoni, Sausage, GroundBeef, Olives,
    Pineapple, ExtraCheese, Onions, GreenPepper;
    int NumberOfToppings;
    double PricePizza, PriceToppings, PriceTotal;
    const double PriceEachTopping = 0.45;

    // Get the price of the pizza based on the selected size
    if( rdoSmall->Checked == True )
    PricePizza = 8.65;
    else if( rdoMedium->Checked == True )
    PricePizza = 9.55;
    else if( rdoLarge->Checked == True )
    PricePizza = 10.75;

    // Check each item.
    // If a check box is on an item, the item counts as one
    // If an item is not checked, count it as 0
    if( lstToppings->Checked[0] == True )
    Pepperoni = 1;
    else
    Pepperoni = 0;

    if( lstToppings->Checked[1] == True )
    Sausage = 1;
    else
    Sausage = 0;

    if( lstToppings->Checked[2] == True )
    GroundBeef = 1;
    else
    GroundBeef = 0;

    if( lstToppings->Checked[3] == True )
    Olives = 1;
    else
    Olives = 0;

    if( lstToppings->Checked[4] == True )
    Pineapple = 1;
    else
    Pineapple = 0;

    if( lstToppings->Checked[5] == True )
    ExtraCheese = 1;
    else
    ExtraCheese = 0;

    if( lstToppings->Checked[6] == True )
    Onions = 1;
    else
    Onions = 0;

    if( lstToppings->Checked[7] == True )
    GreenPepper = 1;
    else
    GreenPepper = 0;

    // Calculate the total number of items that have a check mark
    NumberOfToppings = Pepperoni + Sausage + GroundBeef + Olives +
    Pineapple + ExtraCheese + Onions + GreenPepper;
    // Calculate the total price of toppings
    PriceToppings = NumberOfToppings * PriceEachTopping;
    // Calculate the total price of the order
    PriceTotal = PricePizza + PriceToppings;

    // If only one topping is selected, there is no need to specify
    // how the toppings would be distributed
    if( NumberOfToppings == 1 )
    {
    rdoMixToppings->Enabled = False;
    rdoHalfAndHalf->Enabled = False;
    rdoThirdAnd2Thirds->Enabled = False;
    edtThirdEach->Enabled = False;
    }
    // If two toppings are selected, give the customer the option of
    // 1) mixing both toppings on the pizza
    // 2) putting each topping on one 1/2 of the pizza
    // 3) putting one topping on 1/3 of the pizza and the other topping on 2/3
    else if( NumberOfToppings == 2 )
    {
    rdoMixToppings->Checked = True;
    rdoMixToppings->Enabled = True;
    rdoHalfAndHalf->Enabled = True;
    //rdoThirdAnd2Thirds->Checked = False;
    rdoThirdAnd2Thirds->Enabled = True;
    edtThirdEach->Checked = False;
    edtThirdEach->Enabled = False;
    }
    // If three toppings are selected, let the user decides
    // 1) to mix toppings on the pizza
    // 2) to lay each topping on 1/3 of the pizza area
    else if( NumberOfToppings == 3 )
    {
    rdoMixToppings->Checked = True;
    rdoMixToppings->Enabled = True;
    rdoHalfAndHalf->Enabled = False;
    rdoThirdAnd2Thirds->Enabled = False;
    edtThirdEach->Enabled = True;
    }
    // If more than three toppings are selected, the only solution is
    // to distribute them on the whole pizza area
    else if( NumberOfToppings > 3 )
    {
    rdoMixToppings->Checked = True;
    rdoMixToppings->Enabled = True;
    rdoHalfAndHalf->Enabled = False;
    rdoThirdAnd2Thirds->Enabled = False;
    edtThirdEach->Enabled = False;
    }

    edtPizzaPrice->Text = FloatToStrF(PricePizza, ffFixed, 6, 2);
    edtPriceToppings->Text = FloatToStrF(PriceToppings, ffFixed, 6, 2);
    edtTotalPrice->Text = FloatToStrF(PriceTotal, ffFixed, 6, 2);
    }
    //---------------------------------------------------------------------------
  3. On the form, double-click the Small, the Medium, and the Large radio buttons
  4. Implement them as follows:
    //---------------------------------------------------------------------------
    void __fastcall TForm1::rdoSmallClick(TObject *Sender)
    {
    // Let the OnClickCheck of the Check List Box perform the calculations
    lstToppingsClickCheck(Sender);
    }
    //---------------------------------------------------------------------------
    void __fastcall TForm1::rdoMediumClick(TObject *Sender)
    {
    // Let the OnClickCheck of the Check List Box perform the calculations
    lstToppingsClickCheck(Sender);
    }
    //---------------------------------------------------------------------------
    void __fastcall TForm1::rdoLargeClick(TObject *Sender)
    {
    // Let the OnClickCheck of the Check List Box perform the calculations
    lstToppingsClickCheck(Sender);
    }
    //---------------------------------------------------------------------------
  5. Test the application:
  6. After using the form, close it and return to Borland C++ Builder
  7. Save All

 

 

Previous Copyright © 2005-2007 Yevol Next