SIGN UP MEMBER LOGIN:    
ARTICLE

Using MaskedTextBox Control

Posted by Sivaraman Dhamodaran Articles | Windows Controls C# February 21, 2012
The Masked TextBox control is useful for getting input from the user in a restricted and expected format. We will look at this control in this article.
Reader Level:

1. Introduction

 

The Masked Edit control is a special form of the edit control. In the edit control the user enters the data and we do validation and manipulate that data to a specific format if required before persisting that information into the database. But, the masked edit control takes the data in a formatted way and also validates the keyed-in data. Say for example we you expect a number; you can reject all other key INS.

 

The mask property controls the data format and data character validation. Like the text box control, the output from the masked edit is also read from the text property. Have a look at the following depiction:

 

Pic01.JPG

 

First the edit box is set with the Mask property and the property is used to educate the control so that it can know what key press should be processed to take it is as input. In the above picture, 9 specifies that we expect a number in the placeholder as optional. That means that when something is entered it should be a number. Since it is optional, the user does not need to fill all the placeholders. In the following the mask property box is in the picture; a red text box is shown and that is exactly what the user will see in the edit box. It gives him/her knowledge (Of course also with label Phone No: in front of it) of what needs to be entered (and in what format the text box is expecting it).

 

2. About the Sample

 

The screen shot of the sample for the Masked Edit is shown below:

 

Pic02.JPG

 

The first text box looking control is the masked edit control that gets the user input in a structured way. There are some sample masks in the radio group which will allow you to set different mask for the masked edit control. You can actually provide your own format based on the need. The Show Output button will extract the text content from the masked edit and display it in the text box control next to it.

 

Hide Mask on Leave check box shows the mask format in the control when the input focus is set to the control. Beep on Error informs the masked edit control to make the beep sound when a wrong character is entered in the masked edit box. Include literal and include Prompt will control the text output from the mask control to skip the literal character or the prompt letters. In the picture at section you can see what are the literal and prompt characters. The sample also allows you to set a different prompt character at runtime using a single character masked edit control (Look at the bold values of properties to know the properties set to it. The set button will set the prompt character for the big masked edit control at the top of the form.

 

This is a simple sample and all we did is assigning the properties to show how the masked edit is useful and how it saves time when you need a formatted input and need for validation like I need only characters or numbers like that. OK. Let us start exploring the code and I am leaving the form design to you and its simple drag drop of some controls.

 

3. The Mask property

 

This is the heart of the Masked Edit control and this property tells the masked edit how it should behave and what input key it should process and what it should not. Look at the radio group and the first one says it expects some number and the fourth one says it expects a number (Again) in the form of hour, minute, seconds.

 

Let us take the fourth mask. The zeros in the mask say that a number (0-9) should be entered and the colon ':' is the literal that cannot be changed. So when user types the time they do not need to type the colons as it already there in the required position.

 

The following are the letters that you can mix with the literals:

  • # - You can type +/- [Optional]

  • 0 - Digit zero to 9 [Required]

  • 9 - Digit 0 - 9 [Optional]

  • A - Alpha Numeric. [Required]

  • a - Alpha Numeric. [Optional]

  • L - Letters a-z, A-Z [Required]

  • ? - Letters a-z, A-Z [Optional]

  • C - Any non-control character [Optional]

You can refer to the documentation for more mask letters. But, this is enough to frame a mask to get the controlled input. As you see, each character has a meaning and accepts a rule. Say for example, the character 0 states that it only accepts the number. OK. What if the user types M in the placeholder for 0? The input is not accepted. What is Optional and Required? When we type an invalid character in the placeholder the keyed-in character is skipped. This may make you think that you cannot move to the next character until the required characters are filled. Right?

 

But, this is not how the control behaves. You can still skip the required placeholder and take the output from the masked edit control. Then how does the control respond when the required character is not filled? Well. It sets the MaskCompleted property only when the required mask characters placeholders are filled. This property doesn't care about the optional mask characters. The MaskFull property is set to true when all the required as well as optional placeholders in the mask are filled.

 

The following is the code (handler for radio buttons) for setting the mask property:

 

//Mask 001: Set different Masks based on the selected radio buttons.

//              These masks control the output in a specific format.

private void radMask1_CheckedChanged(object sender, EventArgs e)

{

    maskedInput.Mask = radMask1.Text;

}

 

private void radMask2_CheckedChanged(object sender, EventArgs e)

{

    maskedInput.Mask = radMask2.Text;

}

 

private void radMask3_CheckedChanged(object sender, EventArgs e)

{

    maskedInput.Mask = radMask3.Text;

}

 

private void radMask4_CheckedChanged(object sender, EventArgs e)

{

    maskedInput.Mask = radMask4.Text;

}

 

private void radMask5_CheckedChanged(object sender, EventArgs e)

{

    maskedInput.Mask = radMask5.Text;

}

 

The following code shows the usage of the mask completed property. We examine the textchanged event of the masked edit control and display the mask-completed label when the MaskCompleted property is set to true.

 

We just set the caption text of the radio control to the mask property of masked edit control. The following is the video that shows how the mask is shown to the user and how do we use the mask completed property.

 

//Mask 007: Show the Mask Completed label when required input is completed.

private void maskedInput_TextChanged(object sender, EventArgs e)

{

    if (maskedInput.MaskCompleted == true)

        lblMaskCompleted.Visible = true;

    else

        lblMaskCompleted.Visible = false;

}

 


Video: Online streaming

 

4. Hiding the mask on Leave

 

The Hide HidePromptOnLeave property is used to hide the prompt character when we leave the masked edit control. In other words, the prompt characters are shown only when we set focus to the control. The following is the code for it:

 

//Mask 003: Hides the prompt chars on the mask when we leave the control

private void chkHideMsk_CheckedChanged(object sender, EventArgs e)

{

    maskedInput.HidePromptOnLeave = chkHideMsk.Checked;

}

 

How the above code changes the Masked edit control is shown in the following video.

 


Video: Online streaming

 

5. Beep on Error

 

The BeepOnError property makes a bell sound if only PC sounds are available. If you have a proper sound card then it plays a sound file (.Wav) for the error. You can set a different error sound in the control panel for sound option. The following is the code that sets the BeepOnError to true when the checkbox is in the checked state.

 

//Mask 004: When user enters the invalid char raises the beep (Or plays corrosponding .wav file

//               when external sound device is connected)

private void chkBeepErr_CheckedChanged(object sender, EventArgs e)

{

    maskedInput.BeepOnError = chkBeepErr.Checked;

}

 

6. Setting different prompt char

 

The PromptChar property is used to set a different prompt character to the Masked edit control. In the sample a masked edit control is used to set the prompt character. And the mask prperty for the text box is a single C. That means you can enter only one character and that can be any character except the control keys. Have a look at the properties set (Bold values) for the small edit box after downloading the sample. The following is the code that sets a different prompt character to the masked text box control by changing it from the default, which is underscore (_).

 

//Mask 006: Setting the different mask prompt charactor

private void btnSet_Click(object sender, EventArgs e)

{

    maskedInput.PromptChar = System.Convert.ToChar(txtmskPromptChar.Text);

}

 

In the code we are converting the entered text (Single character) to Char data type as that is what is expected by the property PromptChar. The following video shows the above code with the PromptChar property in effect.
 


Video: Online streaming

 

7. TextMaskFormat Property

 

Go back to the section 1 of this article and have a look at the depiction to know what is Prompt character and what is mask literal. The text property will retrieve the value entered in the masked edit control and when retrieving you can actually skip or allow those prompts and mask literals. The textMaskFormat property informs the masked edit control, how the output from the control should be extracted from the masked edit control. The following is the code that shows the usage of this property.

 

//Mask 005: When we take the output from mask control, we have the option of skipping the

//              Prompt and/or literal.

private void chkIncludeLiteral_CheckedChanged(object sender, EventArgs e)

{

    SetOutputFormat();

}

 

private void chkIncludePrompt_CheckedChanged(object sender, EventArgs e)

{

    SetOutputFormat();

}

 

private void SetOutputFormat()

{

    if (chkIncludeLiteral.Checked == true)

    {

        if (chkIncludePrompt.Checked == true)

        {

            maskedInput.TextMaskFormat = MaskFormat.IncludePromptAndLiterals;

        }

        else

        {

            maskedInput.TextMaskFormat = MaskFormat.IncludeLiterals;

        }

    }

    else

    {

        if (chkIncludePrompt.Checked == true)

        {

            maskedInput.TextMaskFormat = MaskFormat.IncludePrompt;

        }

        else

        {

            maskedInput.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;

        }

    }           

}

 

By setting the proper contant value from the MaskFormat to the TextMaskFormat property, you can control how you want to extract the data entered in the masked edit control. The video below is showing how the output is changed by including or skipping the Prompt and literal characters.

 


Video: Online streaming

 

The masked text box control is useful when we want to educate the user of what format the input is expected from them. The mask character does not allow entering invalid haracters in the placeholder. In the mean time it allows skipping the placeholder for a required character by not entering anything. So the coder should make use of the MaskCompleted property to make sure all required character placeholders are filled. Finally we have the option for specifying what format we want to store the output and this format is controlled by the TextMaskFormat property.

 

End.

Login to add your contents and source code to this article
share this article :
post comment
 

Hi Sivaraman Dhamodaran, Thanks for good article. I am facing some problems with maskededit control. I have applied that control on textbox for formatted zip code. It is not allowing backspace/deleting in safari and chrome but it is working in IE and firefox. Is there any solution for that? I hope, you are able to solve it. Thanks in advance.

Posted by Asvad Sumra Mar 23, 2012

You should wait for streaming to complete 100%. It may take time based on the browser's speed. Alternatively you can download the videos from the Blog section. Click my profile name and go to the blog section. I provided the links, but the editor of the articles removed it.

Posted by Sivaraman Dhamodaran Feb 26, 2012

I'am unable to view the video streaming.do we need any specific system Requirements?Please help.

Posted by Selvi Feb 23, 2012

Thank You

Posted by Sivaraman Dhamodaran Feb 23, 2012

Good Work...

Posted by Aaron Cronje Feb 23, 2012
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor