Windows Controls: The Edit Control


Introduction to Edit Controls



An edit box is a Windows control used to get or display text for the userís interaction. At its most regular use, an edit box serves as a place to fill out and provide information. Such a use is common on employment applications, login dialog boxes, etc.

Like most other controls, the role of an edit box is not obvious at first glance; that is why it should be accompanied by a label that defines its purpose. From the userís standpoint, an edit box is named after the label closest to it. Such a label is usually positioned to the left or the top side of the edit box. From the programmerís point of view, an edit box is a placeholder used for various things. For example, you can show or hide it as you see fit. You can also use it only to display text without allowing the user to change it.


Practical LearningPractical Learning: Introducing Edit Controls

  1. Start Embarcadero RAD Stutio
  2. To create a new project, on the main menu, click File -> New -> VCL Forms Application - C++Builder
  3. In the Object Inspector, change the properties of the form as follows:
    Caption: Sphere Evaluation
    Name: frmEvaluation
    Position: poScreenCenter
  4. In the Tool Palette, click Additional
  5. Click TBevel TBevel and draw a rectangle
  6. In the Object Inspector, change the Style to bsRaised
    If you want to save the project, on the main menu, click File -> Save All. Click the New Folder button. Set the name to SphereEvaluation1 and press Enter twice to select the new folder. Set the name of the unit to Evaluation and press Enter. Set  the name of the project to SphereEvaluation and click Add

Creating an Edit Control

To create an edit box, once again, C++Builder provides a lot of choices. The most fundamental edit box is designed with the TEdit control Edit of the Standard section of the Tool Palette. The TEdit class is based on the TCustomEdit class that itself is derived from TWinControl:

TEdit Inheritance

Practical LearningPractical Learning: Creating an Edit Control

  1. In the Tool Palette, click Standard
  2. Click TEdit and click inside the bevel on the form

Primary Characteristics of Edit Controls


The Text of an Edit Control

The most important aspect of an edit box is its text, whether it is displaying or requesting it. This is the Text property. When you add an edit control, C++Builder initializes it with the name of the control; this would be Edit1 for the first edit box, Edit2 for the second, etc. If you want the control to display some text when the form launches, type the text in the Text property field in the Object Inspector. Otherwise, if you want the edit box to be empty when it comes up for the first time, delete the content of the Text field.

Practical LearningPractical Learning: Specifying the Text of an Edit Control

  1. On the form, make sure the edit control is still selected.
    In the Object Inspector, click Text, type 0.00 and press Enter
  2. Still in the Object Inspector, click Name, type edtRadius and press Enter
  3. Complete the design of the form as follows:
    Sphere Evaluation
    Control Caption Name Text
    TBevel TBevel      
    TLabel Label Radius:    
    TEdit TEdit   edtRadius 0.00
    TLabel Label Diameter:    
    TEdit TEdit   edtDiameter 0.00
    TLabel Label Circumference:    
    TEdit TEdit   edtCircumference 0.00
    TLabel Label Area:    
    TEdit TEdit   edtArea 0.00
    TLabel Label Volume:    
    TEdit TEdit   edtVolume 0.00

The Maximum Length

By default, the user can enter considerably long text in an edit control. To let you control the maximum number of characters that the edit control can hold,  the TCustomEdit class is equipped the MaxLength property:

__property int MaxLength = {read=FMaxLength,write=SetMaxLength};

The Text Alignment

By default, an edit control starts displaying its text to the left side. Still, you have the option of positioning it to the left, the center, or the right side. This characteristic is controlled by the Alignment property of the TCustomEdit class. At design time, to specify it, use the Object Inspector. Otherwise, to programmatically specify the alignment of the text, assign the desired value to the Alignment property.

Practical LearningPractical Learning: Aligning Text

  1. On the form, click the Radius edit control (the edit control on the right side of Radius)
  2. Press and hold Shift
  3. Click each of the other edit controls
  4. Release Shift
  5. In the Object Inspector, click Alignment, then click its arrow and select taRightJustify
    Sphere Evaluation

A Read-Only Edit Control

By default, a newly created edit box is used to both display and receive text from the user. If you want to user to read text without being able to change it, set the ReadOnly Boolean property to true. Its default value is false.

As mentioned already, an edit box should be accompanied by a label that indicates what it is used for. To support this relationship, the Label control provides various properties. An accelerator character is a symbol of the label that provides easy access to its edit box. On the label, such a character is underlined. An example would be First Name. The idea is that, if the user presses Alt key in combination with the labelís underlined characters, the edit box it accompanies would receive focus.

Practical LearningPractical Learning: Setting the Read-Only Attribute

  1. On the form, click the Diameter edit control (the edit control on the right side of Diameter)
  2. Press and hold Shift
  3. Click each of the other edit controls under it (not including the Radius edit control)
  4. Release Shift
  5. In the Object Inspector, click the check box of ReadOnly to change it to False

The Accelerator of an Edit Control

To create an accelerator key, choose one of the labelís characters and precede it with an ampersand character when setting its caption. An example would be &First Name. If you want a label to display the accelerator character instead of a plain ampersand, set the labelís ShowAccelChar property to true. If you set it to true but need to display an ampersand, type two & characters where the ampersand would be shown.

The ShowAccelChar property of a label is only used to indicate that the label will display an accelerator character and the & symbol typed on the label creates that accelerator character. To indicate which edit box would receive focus when the accelerator character of the label is invoked, the label control provides the FocusControl property. To use this property, select the label on the container. Then, on the Object Inspector, click the FocusControl field to display its combo box. From there, you can select one of the existing controls. The control, such as an edit box, must be able to receive focus.

Practical LearningPractical Learning: Creating an Accelerator Key

  1. On the form, click the Radius label
  2. In the Object Inspector, change its Caption to &Radius:
  3. Click FocusControl and click the arrow of its box. Select edtRadius

Edit Control Events


Getting Focus

The Edit control is equipped with many events. Some of these events are from its parent class the TCustomEdit class and some others are from ancestor classes.

An edit control shows that it has focus when the caret blinks in it. To use an edit control, the user can click it. When this happens the control fires an OnClick event. If the form or container has many controls, the user can press Tab continuously until the caret displays in the edit box. In this case, the control would fire an OnEnter event.

Losing Focus

After using the edit control, the user can click another control or the user can press Tab. In both cases, the edit control that had the caret loses focus. At this time, the control fires an OnExit event.

Practical LearningPractical Learning: Using the Lost Focus

  1. On the form, click the Radius edit control
  2. In the Object Inspector, click Events and double-click OnExit
  3. Implement the event as follows:
    #include <vcl.h>
    #include <math.h>
    #pragma hdrstop
    #include "Evaluation.h"
    #pragma package(smart_init)
    #pragma resource "*.dfm"
    TfrmEvaluation *frmEvaluation;
    __fastcall TfrmEvaluation::TfrmEvaluation(TComponent* Owner)
    	: TForm(Owner)
    void __fastcall TfrmEvaluation::edtRadiusExit(TObject *Sender)
        double dRadius = 0.00;
        try {
    	dRadius = StrToFloat(edtRadius->Text);
    	edtDiameter->Text = FloatToStrF(dRadius * 2,
    					ffFixed, 12, 5);
    	edtCircumference->Text = FloatToStrF(dRadius * 2 * M_PI,
    					     ffFixed, 12, 5);
    	edtArea->Text = FloatToStrF(dRadius * dRadius * 4.0 * M_PI,
    				    ffFixed, 12, 5);
    	edtVolume->Text = FloatToStrF(dRadius * dRadius *
    				      dRadius * 4.0 * M_PI / 3.00,
    				      ffFixed, 12, 5);
        catch (EConvertError *)
    	ShowMessage(L"The value you provided for the radius is not acceptable");
  4. Press F9 to execute
  5. In the radius edit box, enter a number, such as 48.69 and press Tab
    Sphere Evaluation
  6. Close the form and return to your programming environment
  7. On the main menu, click File -> Close All
  8. When asked whether you want to save, if you had decided to save the project, click Yes. Otherwise, click No

Changing the Text

The OnChange() event occurs as the user is typing text in the control. This happens as the user is changing the content of an edit control; this sends a message that the content of the edit box has changed or has been updated. You can use this event to check, live, what the user is doing in the edit box. For example, if you create a dialog with a first and last names edit boxes, you can use another edit box to display the full name. The controls could be drawn as follows:

You can implement the OnChange event of the first name edit box as follows:

void __fastcall TfrmPersInfo::edtFirstNameChange(TObject *Sender)
	edtFullName->Text = edtFirstName->Text + " " + edtLastName->Text;

When the second edit box is being edited, you can implement its OnChange event as follows:

void __fastcall TfrmPersInfo::edtLastNameChange(TObject *Sender)
	edtFullName->Text = edtFirstName->Text + " " + edtLastName->Text;

Practical LearningPractical Learning: Changing the Text of an Edit Control

  1. To create a new application, on the main menu, click File -> New -> VCL Forms Application - C++Builder
  2. In the Tool Palette, click Standard
  3. Click TEdit and click the form
  4. In the Object Inspector, click Text and press Delete
  5. Click Font and click its ellipsis button
  6. Select the following options:
    Font: Georgia
    Font style: Bold
    Size: 24
    Color: Blue
  7. Click OK
  8. On the form, right-click the edit control -> Edit -> Copy
  9. Right-click the form -> Edit -> Paste
  10. On the form, double-click the first text box to generate its OnChange event
  11. Implement it as follows:
    void __fastcall TForm1::Edit2Change(TObject *Sender)
    	Edit2->Text = Edit1->Text;
  12. Press F9 to test the application
  13. When the form comes up, type a few characters
  14. Besides the character keys, press the Backspace, the Space, the Shift, the Home, and other keys while typing
  15. Close the form and return to your programming environment
  16. On the main menu, click File -> Close All
  17. When asked whether you want to save the project, click No

Using the Keyboard Events

The edit control recognizes all the events associated with the keyboard and these are particularly important because the edit box is the most commonly used control for typing. All three keyboard events are dealt with sequentially when the user types. When the user presses a key to type, the control fires an OnKeyDown event. As soon as the user releases the key, the control fires an OnKeyUp event. If you want to find out what key the user had pressed, use the OnKeyPress event.

Practical LearningPractical Learning: Using a Keyboard Event

  1. To create a new application, in the Tool Palette, click C++Builder Projects and double-click the VCL Forms Application icon
  2. In the Tool Palette, click Standard
  3. Click TEdit and click the form
  4. On the form, make sure the edit control is still selected.
    In the Object Inspector, click Text, type write.exe and press Enter
  5. Still in the Object Inspector, click Events
  6. Double-click the right side of OnKeyPress
  7. In the top section of the file, under #include <vcl.h>, type #include <stdio.h>
  8. Scroll down and implement the event as follows:
    void __fastcall TForm1::Edit1KeyPress(TObject *Sender, wchar_t &Key)
        char strURL[100];
        if( Key == VK_RETURN )
    	sprintf(strURL, "%s", Edit1->Text.t_str());
  9. Press F9 to execute and test the application
  10. When the form opens, press Enter
  11. Close WordPad
  12. In the text box, replace the text with the address of a web site, such as http://www.embarcadero.com, and press Enter
  13. Close the form and return to your programming environment
  14. On the main menu, click File -> Close All
  15. When asked whether you want to save the project, click No

Additional Characteristics of Edit Controls


A Modified Edit Control

To use an edit control, the user can enter text or change the text in it. To keep track of the changes, the TCustomEdit class is equipped with a Boolean property named Modified and that its child controls inherit:

__property bool Modified = {read=GetModified,write=SetModified};

You can programmatically acknowledge that the control has been modified by setting the Modified property to true.

Whenever the user changes the text in the edit control, the control fires an event named OnChange. This event is of type a TNotifyEvent type. This event is useful if you want to display a notification that the text is not as it was when the form opened.

The Character Case

The CharCase property of an edit control allows the content of a text box to apply a character case of your choice. The CharCase property is controlled by the TEditCharCase enumerator defined as follows:

enum TEditCharCase { ecNormal, ecUpperCase, ecLowerCase };

By default, it is set to ecNormal, which respects whatever character case is typed in an edit box. Otherwise, you can set it to ecUpperCase or ecLowerCase to set the edit boxí characters to uppercase or lowercase respectively.

The Password Character

Text typed in an edit box appears with its corresponding characters unless you changed the effect of the CharCase property from ecNormal. This allows the user to see and be able to read the characters of an edit. If you prefer to make them un-readable, you can use the PasswordChar property. Although this property is a char type of data, changing it actually accomplishes two things. Its default value is #0, which means that the characters typed in it will be rendered in their alphabetic corresponding and readable characters. If you change it, for example to *, any character typed in it would be un-readable and be replaced by the value of this property. You can use any alphabetic character or digit to represent the characters that would be typed but you must provide only one character. Alternatively, you can specify an ASCII character instead. To do this, type # followed by the number representing the ASCII character. For example, #98 would display b for each character.

Selecting the Content of an Edit Control

When using a form, the user can press Tab to move from one control to another. By default, when such a control receives focus from the user pressing Tab, the whole text in an edit control is selected. This is controlled by the AutoSelect property. If you do not want that, you can set the AutoSelect Boolean property to false.

One of the actions the user may be asked to perform on an edit box is to type text in it. If the control already contains text, the user can read it. Another common action the user performs is to select text contained in the control. The user must have the option to select only part of the text or its whole content. To do this, the user can click and hold the mouse on one end of the selection and drag to the desired end. This allows for partial selection. The area where the user start dragging during selection is represented by the SelStart property. When the user ends the selections, the length of the text selected is represented by the SelLength property. The portion of text selected is represented by the SelText property, which is an AnsiString type. These properties allow you either to programmatically select text or to get information about text that the user would have selected in the edit box.

Selecting Text

The edit control is based on the TEdit class whose immediate parent is TCustomEdit. Like every VCL class, it has a constructor and a destructor. The constructor can be used to dynamically create an edit control. The TEdit class provides other methods derived from the controlís parent or from ancestor classes.

We saw earlier the properties related to the selection of text from an edit control performed either by you or by a user. Alternatively, the user may want to select the whole content of the control. To programmatically select the whole text of an edit control, call the SelectAll() method. Its syntax is:

void __fastcall SelectAll();

If the user or another control or action had selected text on the edit control, you can delete the selection using the ClearSelection() method of the TCustomEdit class. Its syntax is:

void __fastcall ClearSelection(void);

This method first finds if some text is selected. If so, the selected text would be discarded. If nothing is selected, the method would not do anything. To delete a selected text, you can write:

void __fastcall TForm1::btnClearSelectionClick(TObject *Sender)

Clearing the Control

The contents of an edit box can be empty or contain some text. If you want it empty, use the Clear() method of the TCustomEdit class. Its syntax is:

virtual void __fastcall Clear(void);

This would delete the whole contents of the control:

void __fastcall TForm1::btnClearClick(TObject *Sender)

Using the Clipboard

The edit control natively supports regular operations performed on a text control such as undoing an action, cutting or copying text from the control, pasting text from another control. The methods used to accomplish these assignments are Undo(), CutToClipboard(), CopyToClipboard(), PasteFromClipboard(). Their syntaxes are:

void __fastcall Undo(void);
void __fastcall CutToClipboard(void);
void __fastcall CopyToClipboard(void);
void __fastcall PasteFromClipboard(void);

Home Copyright © 2010-2011 FunctionX, Inc.