AddThis Social Bookmark Button

Print
Liberty on Whidbey

Enhanced Text Input in Windows Forms 2.0

by Jesse Liberty
03/14/2005

Visual Studio 2005 provides enhanced controls for managing data input in Whidbey. To get started, let's take a look at the masked editing control that allows you to restrict the input from a user that a Windows Form will accept and to control how it is displayed by using a mask. For example, you might wish to use a telephone mask so that when a user enters "6175551212," the mask will render the input as "(617) 555-1212."

A mask can block invalid characters (such as the % sign) and can signal to the user what is expected (e.g., the parentheses indicate that an area code is required). To see this at work, create a new application (call it TextInput). Drag a MaskedTextBox control onto the form created by the Visual Studio designer. Click the Smart tab and choose the one action available: "Set Mask." The Input Mask dialog opens, as shown in Figure 1:


Figure 1
Figure 1. Using a masked input

As you can see, .NET 2.0 provides you with a number of standard masks. Choose the "Phone number mask;" the mask itself appears in the Mask text box, and you are invited to try out the mask in the "Try it" text box, as shown in Figure 2.

Figure 2
Figure 2. Specifying input mask

If you are happy with the mask you've selected, click the OK button, and the mask you have selected is associated with the Mask control. Add a label control to provide context. Click on the MaskedTextBox control and examine the properties window; you'll find a few very useful properties, among them:

Mask

The mask you've chosen. If you click on the ellipses, the Mask Input dialog box reopens. You are also free to type in your own custom mask.

BeepOnError

If the user types an invalid character and this is set to true, the computer emits the standard error tone. The default is false.

PromptChar

Until the mask is filled, each missing character is replaced with this character. The default is the underscore.

 

Replacing the PromptChar default character with a question mark (?) changes the prompt character displayed in the mask, as shown in Figure 3:

Figure 3
Figure 3. Masked edit in action

When you interact with the MaskedTextBox control programmatically, you can test its MaskCompleted property, which returns true only if there are no empty characters in the mask. When you want to retrieve the text from the MaskedTextBox, you can access the Text property. To see this at work, add three new controls to the form:

Control Type ControlID Text
Checkbox cbMaskCompleted "Mask Completed"
Label lblText "Text"
TextBox txtInput  

Create an event handler for the TextChanged event of the MaskedTextBox:


Private Sub MaskedTextBox1_TextChanged( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MaskedTextBox1.TextChanged
    cbMaskComppleted.Checked = MaskedTextBox1.MaskCompleted
    txtText.Text = MaskedTextBox1.Text
End Sub

As you enter code, the other controls are updated, as shown in Figure 4:

Figure 4
Figure 4. The raw text from the masked edit

Creating Your Own Masks

You can create your own custom masks using the mask characters shown in the following table:

Character Mask value

0 (zero)

Required digit

9

Optional digit

A

Required alphanumeric

a

Optional alphanumeric

&

Required Unicode character

C

Optional Unicode character

#

Optional digit or space or plus or minus symbol

L

Required letter (a-z, A-Z)

?

Optional letter

. (period)

Decimal place holder

, (comma)

Thousands place holder

$

Currency symbol

: (colon)

Separate time values

/ (forward slash)

Separate date values

< (less than)

Force to lower case

> (greater than)

Force to upper case

Auto-Completion Text Boxes

When you type a URL into Internet Explorer, it attempts to help you complete the address by providing a list of addresses that match what you've typed so far. The newly updated TextBox and ComboBox controls provided with Visual Studio 2005 allow you to add that functionality to your Windows Forms, as well.

Drag one more control onto your form, a TextBox named "txtAutoComplete." Click on the new TextBox and then in the properties window, drop down the AutoComplete property, as shown in Figure 5 (I've blanked out some surrounding text to make this easier to see):

Figure 5
Figure 5. AutoCompleteMode property

There are three modes for auto-completion:

Mode Meaning

Suggest

Display the drop-down menu populated with one or more suggested completion strings.

Append

Appends the remainder of the most likely candidate string (highlighted).

SuggestAppend

Combines both of the above.

Choose Suggest for this example. There is one more property you must set for AutoComplete to work: you must specify where to get the list of suggestions. You do so in the AutoCompleteSource property, as shown in Figure 6:

Figure 6
Figure 6. AutoCompleteSource property

There are seven possible sources:

Source Meaning

FileSystem

Recently entered file paths

HistoryList

Taken from IE's history list

RecentlyUsedList

All documents in the "most recently used list" in the Start menu

AllUrl

All sites recently visited

AllSystemSources

All URLs and all files

CustomSources

Items in the AutoCompleteCustomSource collection that you populate either at design time or programmatically

ListItems

Not valid with Text box. Used with ComboBox to pick from items in the ComboBox Items collection

Having chosen AllUrl, your text box will behave much like the text box in Internet Explorer, as shown in Figure 7:

Figure 7

Figure 7. AutoComplete suggestions

You can also create custom enumerations to serve as the source for auto-completion. Just create a custom source at design time by setting the AutoCompleteSource property to CustomSource, and click on the AutoCompleteCustomSource property to fill in the string collection with whatever strings you want to appear in the drop-down menu of suggestions (you can, of course, add to this collection programmatically, as well).

Jesse Liberty is a senior program manager for Microsoft Silverlight where he is responsible for the creation of tutorials, videos and other content to facilitate the learning and use of Silverlight. Jesse is well known in the industry in part because of his many bestselling books, including O'Reilly Media's Programming .NET 3.5, Programming C# 3.0, Learning ASP.NET with AJAX and the soon to be published Programming Silverlight.

Programming C#

Related Reading

Programming C#
Building .NET Applications with C#
By Jesse Liberty

Read more Liberty on Whidbey columns.

Return to ONDotnet.com.