Chapter 3 Readings: 3.1 Reading Input with TextBox Controls
Reading Input with TextBox Controls
Definition and Core Functionality:
A TextBox control is a rectangular area on a form designed to accept keyboard input from the user.
It serves as one of the primary controls for gathering user data required for computational, logical, or visual operations within an application.
Accessing and Creating Controls in Visual Studio:
The TextBox tool is located inside the Toolbox within the Common Controls group.
Double-clicking the TextBox tool places a new TextBox control directly onto the active form.
Newly generated controls are automatically assigned sequential default names, such as
textBox1,textBox2, and so forth.Default control names should always be renamed immediately to meaningful, descriptive identifiers to maintain clear code standards.
Data Storage and the Text Property:
Whatever text a user types into a TextBox control while the application runs is stored inside that control's
Textproperty.Retrieving user input in code requires accessing the contents of the control's
Textproperty.The
Textproperty always returns data as a string.Any standard operation permissible on a string data type can be executed directly on a control's
Textproperty.
Example Implementation (
TextBox Demo):Student sample resources are hosted on the companion website at
www.pearsonhighered.com/gaddisin theChap03directory under the project titleTextBox Demo.Form setup features
nameTextBox,readInputButton, andoutputLabelcontrols.The
Clickevent handler forreadInputButtonperforms the following string assignment:outputLabel.Text = nameTextBox.Text;Mechanics: The assignment takes the text string currently residing in
nameTextBox.Textand places it directly intooutputLabel.Text.Sample Execution: If a user enters
Kathryn SmithintonameTextBoxand clicksreadInputButton, the stringKathryn Smithis transferred and displayed onoutputLabel.
Clearing the Contents of a TextBox Control
Clearing Mechanics:
A TextBox control's visual contents are cleared in the exact same manner as a Label control: by assigning an empty string (
"") to the control'sTextproperty.
Implementation Example:
nameTextBox.Text = "";Execution outcome: Once this statement runs, the
nameTextBoxcontrol will appear completely empty on the running application form.
Checkpoints and Review Questions
Checkpoint 3.1: What control can be used to gather text input from the user?
Answer: The TextBox control.
Checkpoint 3.2: In code, how do you retrieve data that has been typed into a TextBox control?
Answer: By retrieving the contents of the control's
Textproperty.
Checkpoint 3.3: What type of data does a control's Text property always contain?
Answer: A string.
Checkpoint 3.4: How do you clear the contents of a TextBox control?
Answer: By assigning an empty string (
"") to the control'sTextproperty.