Chapter 28 Exercises: Forms, Controls, and Events


Part A: Conceptual Understanding

A.1. Explain the difference between Anchors and Align for layout. When would you use each? Give a specific example form layout that uses both.

Guidance Align attaches a control to fill an entire edge of its parent (alTop fills the top, alClient fills all remaining space). It is best for major structural regions — toolbars, sidebars, status bars. Anchors bind specific edges of a control to corresponding edges of its parent. They are best for controls within a region that should stretch or reposition when the parent resizes. Example: a form with pnlToolbar (Align=alTop), pnlSidebar (Align=alLeft), and pnlContent (Align=alClient). Inside pnlContent, a TStringGrid with Anchors=[akTop, akLeft, akRight, akBottom] stretches to fill the content area, and an OK button with Anchors=[akBottom, akRight] stays in the bottom-right corner.

A.2. What is the difference between a modal and a modeless form? Give two real-world examples of each.

Guidance A modal form blocks the parent window — the user must close it before returning to the main form. Examples: a Save confirmation dialog, a login form. A modeless form coexists with the main form — the user can switch between them freely. Examples: a Find/Replace window, a tool palette. Modal forms use ShowModal and return a ModalResult. Modeless forms use Show and continue execution immediately.

A.3. Why is it important to set TabOrder explicitly on data entry forms? What happens if you do not?

Guidance Tab order controls the sequence in which the Tab key moves focus between controls. If not set explicitly, the default order matches the creation order of controls, which may not match the visual layout. The user expects Tab to move logically — left to right, top to bottom. A form where Tab jumps from the name field to the OK button, skipping email and phone, feels broken and wastes the user's time.

A.4. Explain the three validation strategies (on-submit, on-exit, as-you-type). Which would you choose for an email address field, and why?

Guidance On-submit checks all fields when Save is clicked. On-exit checks each field when it loses focus. As-you-type checks on every keystroke. For email, on-exit is best: the user types the full address, tabs away, and gets immediate feedback if the format is wrong. As-you-type would be annoying because a partially typed email ("user@") is always "invalid." On-submit would delay feedback too long.

Part B: Exploration and Analysis

B.1. Create a form with a TStringGrid (5 columns, 10 rows). Populate it with sample data (student names, grades, etc.). Experiment with these properties and document the behavior of each: Options (goEditing, goRowHighlight, goColSizing, goRowSelect), DefaultRowHeight, AlternateColor, FixedColor.

B.2. Build a form with three panels: one using Align = alLeft (width 200), one using Align = alTop (height 50), and one using Align = alClient. Add a TSplitter between the left panel and the client panel. Now resize the form to various sizes. What happens? What happens when you set Constraints.MinWidth on the form?

B.3. Create a modeless form that acts as a "log window." The main form has a button that, when clicked, adds a timestamped message to a TMemo on the log form. Verify that you can click the main form button while the log window is visible. What happens if you try to close the log form and then click the button?


Part C: Coding Challenges

C.1. Registration Form (Easy) Build a registration form with: Name (TEdit), Email (TEdit), Password (TEdit with PasswordChar), Confirm Password (TEdit with PasswordChar), Country (TComboBox), "I agree to terms" (TCheckBox), Register button, and Cancel button. Validate that: name is not empty, email contains '@', password is at least 8 characters, passwords match, and the checkbox is checked. Display a success message on valid submission.

C.2. To-Do List Manager (Intermediate) Build an application with a TListBox showing tasks, a TEdit for entering new tasks, an "Add" button, a "Delete" button (removes the selected task), a "Mark Done" TCheckBox (prepends "[DONE]" to the selected item), and a TLabel showing the count of incomplete tasks. When a task is marked done, change its color using a custom OnDrawItem handler.

Hints Set ListBox1.Style := lbOwnerDrawFixed to enable custom drawing. In the OnDrawItem event, check if the item text starts with "[DONE]" and set the font color to clGray if so. Use ListBox1.Canvas.TextOut for custom rendering.

C.3. Dynamic Control Creation (Intermediate) Build a "survey builder" where the user can add questions dynamically. The form has a "Add Text Question" button (creates a TLabel + TEdit), an "Add Choice Question" button (creates a TLabel + TRadioGroup), and a "Submit Survey" button that collects all answers and displays them in a TMemo. All question controls are created at runtime.

Hints Track created controls in a TList or array. Each control is created with TEdit.Create(Self) and positioned vertically (increment a Y counter). Set Parent := ScrollBox1 to place them inside a scrollable area (use a TScrollBox as the question container).

C.4. Multi-Form Address Book (Advanced) Build a three-form application: (1) Main form with a TStringGrid listing contacts (Name, Phone, Email). (2) "Add/Edit Contact" modal dialog with fields for Name, Phone, Email, and a TMemo for notes. (3) "Search" modeless dialog with a TEdit and "Find Next" button that highlights matching rows in the main grid. The main form has Add, Edit, Delete, and Search buttons. Edit opens the modal form pre-populated with the selected contact's data.

C.5. PennyWise Enhancement: Category Manager (Advanced) Add a "Manage Categories" modal dialog to PennyWise that lets the user add, rename, and delete expense categories. The dialog has a TListBox of categories, an "Add" button (prompts with InputBox), a "Rename" button, and a "Delete" button (with confirmation). Changes should update the category dropdown on the main form when the dialog closes with OK.


Part M: Metacognitive Exercises

M.1. Which layout technique (anchors, align, or manual positioning) do you find most intuitive? Which is most confusing? Write down one thing you will do to practice the confusing one.

M.2. Look at the PennyWise expense detail form code. Identify every instance of "separation of concerns" — where does UI code end and business logic begin? Where could the separation be improved?

M.3. After completing Exercise C.3 (dynamic controls), reflect: was creating controls in code harder or easier than using the form designer? In what situations would runtime creation be the only option?