This lesson describes how to create and configure text edit controls. TextBox controls are used to both display text to the user and receive textual input. The MaskedTextBox allows you to display text in a preset format and validate user input against a format.
In this lesson, you will learn how to configure the TextBox and MaskedTextBox con
trols to receive and display user input.
After this lesson, you will be able to:
■ Configure the TextBox control to receive editable, multiline input from the user.
■ Configure the MaskedTextBox control for formatted text and data entry.
Estimated lesson time: 30 minutes
The TextBox Control
The TextBox control is the primary control used to receive textual input from the user.
The TextBox allows you to receive text from and display text to the user. You can create text boxes that can display multiline text, and you can create text boxes that display a password character instead of the actual text.
The TextBox control exposes several properties that allow you to configure its behav
ior. Important properties of the TextBox control are shown in Table 2-6.
Table 2-6 Important Properties of the TextBox Control
Property Description
AutoCompleteCustomSource Holds a string collection that contains auto-com
plete data when the AutoCompleteMode is set to a value other than None and the AutoCompleteSource is set to Custom.
AutoCompleteMode Sets the AutoComplete mode of the control. Possi
ble values are None, Append, Suggest, or Suggest- Append.
AutoCompleteSource Sets the source for auto-complete data. Can be set to any of a variety of system sources or to a custom source provided by the AutoCompleteCustomSource property.
Table 2-6 Important Properties of the TextBox Control
Property Description
CharacterCasing Indicates the casing of the characters in the Text- Box control. Possible values are Normal, Upper, or Lower.
Lines Returns a string array representing the individual lines of the text box. This property is most useful when MultiLine is set to True. Note that a line is defined as a string that is terminated by a carriage return character and does not refer to visible lines in the UI as might be seen when the WordWrap property is set to True.
MaxLength Specifies the maximum number of characters that can be entered into the TextBox.
MultiLine Indicates whether the TextBox can contain only a single line of text or multiple lines.
PasswordChar Sets the password character to be displayed in the Textbox instead of the actual characters of the text.
ReadOnly Indicates whether the text in the TextBox can be edited.
ScrollBars Indicates the scroll bars that will be displayed in the TextBox when the MultiLine property is set to True.
Text Gets or sets the text contained in the TextBox.
UseSystemPasswordChar Indicates whether to use the system password instead of the actual text character in the TextBox.
WordWrap Indicates whether words automatically wrap from one line to the next when the MultiLine property is set to True.
The main purpose of the TextBox control is to provide a container for editable text.
Users can input text into text boxes or edit textual data the application displays. The
text held by the TextBox property is accessible via the Text property. The text in the TextBox is editable if the ReadOnly property is set to False, which is the default. If the ReadOnly property is set to True, the user cannot edit the text displayed.
Creating a MultiLine TextBox Control
TextBox controls are single-line by default, but you can create a multiline TextBox by setting the MultiLine property to True. This allows you to resize the TextBox vertically as well as horizontally.
When the MultiLine property is set to True, several other properties become impor
tant. The Lines property exposes a string array that contains the individual lines of the TextBox. The ScrollBars property indicates whether scroll bars will be displayed for the TextBox and, if so, whether Horizontal, Vertical, or both will be displayed. The Word- Wrap property indicates whether words will automatically wrap from one line to the next. Note that if the WordWrap property is set to True, horizontal scroll bars will never appear, even if the ScrollBars property is set to Horizontal.
Creating a Password TextBox Control
You can use the PasswordChar or UseSystemPasswordChar properties to create a text box that can receive text input but display a masking character instead of the actual text, rendering the user input unreadable by observers. This is most commonly used to create a text box for entering a password. If the PasswordChar property is set to a character (for example, an asterisk [“*”]), that character will be displayed whenever the user types a character into the text box. Note that the actual characters the user types will be stored in the Text property—only the rendering of these characters in the UI will change. You can also set the UseSystemPasswordChar property to True, which will display the password character defined by the system for each character typed in the text box. If UseSystemPasswordChar is set to True and PasswordChar is set to a char
acter, the system password character will be used.
The MaskedTextBox Control
The MaskedTextBox control is a modified TextBox that allows you to define a preset pattern for accepting or rejecting user input. The Mask property allows you to specify required or optional characters, or specify whether input characters are letters or numbers, and apply formatting for the display of strings. Important properties of the MaskedTextBox are shown in Table 2-7.
Table 2-7 Important Properties of the MaskedTextBox Control
Property Description
AllowPromptAsInput Indicates whether the prompt character is valid as input.
AsciiOnly Indicates if only ASCII characters are valid as input.
When set to True, only A–Z and a–z are accepted as input.
BeepOnError Indicates whether the MaskedTextBox sends a system beep for every input character it rejects.
CutCopyMaskFormat Determines whether literals and prompt characters are included when the text is cut or copied.
HidePromptOnLeave Indicates whether prompt characters are hidden when the MaskedTextBox loses the focus.
InsertKeyMode Gets or sets the text insertion mode for the Masked- TextBox.
Mask Defines the input mask for the MaskedTextBox (explained in detail in the following text).
PromptChar Gets or sets the character used for the prompt.
RejectInputOnFirstFailure Gets or sets a value indicating whether parsing of user input stops after the first invalid character is reached.
ResetOnPrompt Indicates how an input character that matches the prompt character should be handled.
ResetOnSpace Determines how a space input character should be handled.
SkipLiterals Indicates whether literals in the mask should be reentered or skipped.
TextMaskFormat Indicates whether prompt characters and literal char
acters are included in the text returned by the Text property.
0 9
L
The Mask Property
The most important property of the MaskedTextBox is the Mask property. This prop
erty allows you to define a string that represents the required format of an input string in the MaskedTextBox. The MaskedTextProvider associated with the MaskedTextBox provides the parsing engine that parses the Mask format. The code characters used by the default MaskedTextProvider are shown in Table 2-10.
Table 2-8 Elements of the Default MaskedTextProvider Masking
Element
Description
Represents a required digit between 0 and 9.
Represents an optional digit between 0 and 9.
# Represents an optional digit between 0 and 9, or a space. Plus (+) and minus (–) signs are also accepted.
Represents a required letter, either uppercase or lowercase (A–Z, a–z).
? Represents an optional letter, uppercase or lowercase (A–Z, a–z).
& Represents a required character. If AsciiOnly is set to True, this element behaves like the L element.
C Represents an optional character. If AsciiOnly is set to True, this element behaves like the [?] element.
A, a Represents an optional alphanumeric character. If AsciiOnly is set to True, it will accept only A–Z and a–z.
. Decimal placeholder. Represents a decimal character. The actual character used will be the decimal character that is set by the control’s FormatProvider.
, Thousands placeholder. Represents a thousands separator. The actual character used will be the thousands separator that is set by the control’s FormatProvider.
Table 2-8 Elements of the Default MaskedTextProvider Masking
Element
Description
: Time separator. Represents a time separator. The actual charac
ter used will be the time separator character that is set by the control’s FormatProvider.
/ Date separator. Represents a date separator. The actual character used will be the date separator that is set by the control’s Format- Provider.
$ Currency symbol. Represents a currency symbol. The actual character used will be the currency symbol that is set by the con
trol’s FormatProvider.
< Shift down. Converts all following characters to lowercase.
> Shift up. Converts all following characters to uppercase.
| Disables a previous shift up or shift down.
\ Escapes a mask character, turning it into a literal character. The double slash (\\) is the escape sequence for a backslash.
All other All other characters appear as themselves in the MaskedTextBox characters and cannot be moved or deleted by the user.
You can design a mask for the masked text box by creating a string made of characters described in Table 2-8. Setting the Mask property of the MaskedEditBox restricts the input that is allowed to the format determined by the mask string. Some examples of mask strings, together with input strings and the output string that is displayed in the control, are shown in Table 2-9.
Table 2-9 Examples of Mask Strings
Mask String Input Text Displayed Text (999)-000-0000 1234567890 (123)-456-7890
00/00/0000 07141969 07/14/1969 – Note that the actual date separator displayed will be determined by the control’s FormatProvider.
Table 2-9 Examples of Mask Strings
Mask String Input Text Displayed Text
$99,999.00 1234567 $12,345.00 – Note that the actual cur
rency symbol, thousands separator, and decimal separator will be determined by the control’s FormatProvider.
LL>L|LLL<LL abcdABCD abCdABcd Configuring the MaskedTextBox for User Input
In addition to the Mask property, the MaskedTextBox control has several properties that affect how the control behaves when receiving user input. The AsciiOnly property determines if only ASCII characters are allowed as input; when set to True, it restricts input to A–Z and a–z. Other inputs are rejected. You can set the control to notify users when an error has been committed by setting the BeepOnError property to True. The SkipLiterals property determines whether literal characters should be reentered by the user (if set to False) or skipped over in the MaskedTextBox (when set to True).
The RejectInputOnFirstFailure property governs how text that is pasted into the MaskedTextBox is handled. If a string that does not match the Mask format is pasted into the MaskedTextBox, the MaskedTextBox will reject the entire string if the Reject- InputOnFirstFailure is set to True. If set to False, the MaskedTextBox will accept all the characters that match the Mask format.
The Prompt property sets the character that is displayed in the MaskedTextBox when there is no input for a given position. The default value for the Prompt character is the underscore character ( _ ). The AllowPromptAsInput and ResetOnPrompt properties govern how the prompt character is treated when entered as input. If the ResetOnPrompt property is set to True, prompt characters will be accepted, the Mask will be reset for that character position, and the cursor will advance to the next position. If the ResetOnPrompt property is set to False and the AllowPromptAsInput property is set to True, then the prompt character will be processed as regular input. If both prop
erties are set to False, the prompt character will be rejected. The ResetOnSpace prop
erty governs the treatment of spaces in the same way that ResetOnPrompt governs the treatment of prompt characters.
Manipulating Text in the MaskedTextBox
The text shown in the MaskedTextBox is not necessarily the text that is available to the user when cutting and pasting or to the application when text is manipulated program
matically. The CutCopyMaskFormat determines how the text in the MaskedTextBox is treated when it is cut or copied by the user. The default value for this property is IncludeLiterals, in which case, literals from the Mask are included when text is cut or copied, but prompt characters are not. You can also set this property to ExcludePromptAndLiterals, which excludes both literals and prompts; IncludePrompt, which includes prompt characters but excludes literals; and IncludePromptAndLiter
als, which includes both prompts and literals. The TextMaskFormat property has the same possible values and functions in the same way with respect to the text returned by the Text property.
Quick Check
1. How can you create a TextBox with more than one line?
2. What is the purpose of the MaskedTextBox?
Quick Check Answers
1. You can create a multiline TextBox by setting the MultiLine property to True.
2. The MaskedTextBox control is used to display a format to the user for data entry or display, and to validate that data is input in the correct format.
Lab: Practice with Text Display Controls
In this lab, you will add additional controls to the project you created in Lesson 2. You will add a multi-line textbox to prompt the user for an address, and you will add a MaskedTextBox to collect a phone number.
� Exercise 1: Adding Text Display Controls
1. In Visual Studio, load the solution you completed in Lesson 2 or the completed Lesson 2 solution located on the companion CD in the code folder.
2. In the Solution Explorer, double-click Form2 to open the Designer for Form2.
3. From the Toolbox, drag a TextBox onto the form. Drag a Label onto the form next to the TextBox.
4. Set the Text property of the Label to Address.
5. Set the Multiline property of the TextBox to True and set the WordWrap property to False. Set the ScrollBars property to Both. Resize the TextBoxt to make it large enough to hold an address. From the Toolbox, drag a MaskedTextBox and a Label onto the form.
6. Set the Text property of the Label to Phone Number.
7. Set the Mask property of the MaskedTextBox to (999)-000-0000.
8. C# only. Set the Modifiers property of the TextBox and MaskedTextBox to Internal.
9. In the Solution Explorer, right-click Form1 and choose View Code.
10. In the LinkLabel1_LinkClicked event handler, add the following code to the If block beneath the code you added in Lesson 2.
' VB
MsgBox("Your address is " & Form2.TextBox3.Text)
MsgBox("Your phone number is " & Form2.MaskedTextBox1.Text)
// C#
MessageBox.Show("Your address is " + aForm.textBox3.Text);
MessageBox.Show("Your phone number is " + aForm.maskedTextBox1.Text);
11. Press F5 to run and test your application.
Lesson Summary
■ The TextBox control allows the user to enter text. The text that is entered can be accessed through the Text property.
■ TextBox controls can be single-line or multiline, depending on the value of the MultiLine property.
■ The MaskedTextBox control can be configured for formatted text display and entry.
■ The Mask property determines the formatting for text in MaskedTextBox controls.
Chapter Review
To further practice and reinforce the skills you learned in this chapter, you can perfom the following tasks:
■ Review the chapter summary.
■ Review the list of key terms introduced in this chapter.
■ Complete the case scenarios. These scenarios set up real-world situations involv
ing the topics of this chapter and ask you to create a solution.
■ Complete the suggested practices.
■ Take a practice test.
Chapter Summary
■ Controls are visual components that contain functionality designed to enable common tasks. You can add controls to the designer by dragging them from the Toolbox.
■ The Visual Studio IDE contains several mechanisms for managing the layout of controls on your form, including:
❑ The Properties window.
❑ Layout toolbar.
❑ Snaplines.
❑ Control modification in the designer using the mouse.
❑ Anchor and Dock properties.
■ The Button control is designed to accept user commands and execute code when clicked. You can use the Button_Click and Button_MouseDown events to respond to user clicks.
■ Label controls are primarily used to display read-only text and can be used to create access keys for other controls.
■ The LinkLabel control allows you to create Web-style links that open Web pages or other forms when clicked.
■ The TextBox control is used to receive user input as well as to display text. TextBox controls can be either single-line or multiline.
■ The MaskedTextBox enables you to specify a format for text display or user input.
It enables you to configure how that format restricts user input and how the for
mat is treated during user cut and copy operations.
Key Terms
Do you know what these key terms mean? You can check your answers by looking up the times in the glossary at the end of the book.
■ access key
■ event handler
■ mask
■ snaplines
Case Scenarios
In the following case scenarios, you will apply what you’ve learned about how to use controls to design user interfaces. You can find answers to these questions in the
“Answers” section at the end of this book.
Case Scenario 1: Designing a Simple User Interface
Your organization, Humongous Insurance, is creating an application to help custom
ers calculate the future value of bonds and other investments that will be held for a number of years. As a new employee, you are assigned a simple task: create the front- end interface and prepare the user input to be processed by the calculation engine that will be supplied by another development team. You begin by reviewing the tech
nical requirements.
Technical Requirements
Create a user interface that accepts the following information from users in a simple, straightforward way:
■ Current investment value
■ Assumed interest rate
■ Time span in years
Questions
Answer the following questions for your manager:
1. How can you provide an easy-to-understand interface that provides visual cues to the user, clearly indicates currency when appropriate, and accepts user input for all three of the aforementioned factors?
2. How can you provide a keyboard-based system of navigation as an alternative to mouse use?
Case Scenario 2: Designing a User Interface
Your company has been contracted to design and implement a reservation system for a ski resort and chalet. You have been handed the job of creating a page that is used to enter and display client data. You begin by reviewing the technical requirements.
Technical Requirements
Create a user interface that accepts the following information from users in a simple, straightforward way:
■ First and Last Name.
■ Address.
■ City, state, and Zip Code.
■ Credit card number.
■ A general area for comments about the client.
■ At the bottom of the technical requirements section is a note from the head of security that reads, “We need to be extra careful about our customer credit card information. Make sure it isn’t displayed with the rest of the data.”
Questions
Answer the following questions for your manager:
1. What controls are most appropriate for the design of the user interface?
2. How can you keep customer credit card data from being displayed but still enable its entry?