3.2. Allow Valid Input OnlyVisual Studio 2005 includes a masked editing control in its Toolboxcourtesy of .NET 2.0. It allows you to restrict the input from a user and control how it is displayed by using a mask. For example, you might want 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 %) and can signal to the user what is expected (for example, the parentheses indicate that an area code is required). 3.2.1. How do I do that?Create a new Windows Forms application project, name it MaskedEntry, and drag a MaskedTextBox control to the form created by the Visual Studio Designer. Click the smart tag and choose the one action available: "Set the mask associated with the control." The Input Mask dialog opens, as shown in Figure 3-9. Figure 3-9. Masked text box Input Mask dialogAs you can see, .NET 2.0 provides you with a number of standard masks. Choose the "Phone number" mask; the mask appears in the Mask text box, and you are invited to try it out in the "Try it" text box, as shown in Figure 3-10. Figure 3-10. Trying the "Phone number" maskIf you are happy with the mask you've selected, click the OK button and the mask you selected will be associated with the Mask control, as shown in Figure 3-11. Figure 3-11. A mask associated with MaskedTextBoxIf you click the MaskedTextBox control and examine its properties in the Properties window you'll find a few useful properties, as shown in Table 3-2.
Replacing the PromptChar default character with a question mark (?) changes the prompt character displayed in the mask, as shown in Figure 3-12. Figure 3-12. Changing the prompt characterWhen 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 MaskedTextBox you can access the Text property. To see this at work, add three new controls to the form, as shown in Figure 3-13:
Figure 3-13. The updated mask formCreate an event handler for the TextChanged event on maskedTextBox1: private void maskedTextBox1_TextChanged(object sender, EventArgs e) { cbMaskComplete.Checked = maskedTextBox1.MaskCompleted; txtText.Text = maskedTextBox1.Text; } Each time you enter a character into maskedTextBox1 the other controls will be updated, as shown in Figure 3-14. Figure 3-14. The completed mask3.2.2. What about . . ....creating my own mask? How do I do that? You can create your own mask using the special mask characters shown in Table 3-3.
3.2.3. Where can I learn more?C# Corner has a nice example of using the MaskedTextBox control at http://www.c-sharpcorner.com/Code/2004/Sept/MaskedTextBox.asp. You can find a full description of the properties and nuances of MaskedTextBoxes in the article "MaskedTextBox Class" in the MSDN. |