*** When a New Article posted, get Notification to the email that you give below: ***

Tuesday, February 21, 2012

[C#] - Using MaskedTextbox and Mask property

1. Introduction

Masked Edit control is special form of edit control. In edit control user enter 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 the formatted way and at the mean time in 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 also read from the text property. Have a look at the below depiction:



First the edit box 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 when something entered it should be a number. As it is optional user no need to fill all the placeholders. Below the mask property box in the picture, a red text box 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 need to be 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:



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 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 is literal and prompt chars. The sample also allows you set a different prompt character at runtime using 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 char 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 demo 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 chars 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 it shows the first one says it expects some number and fourth one says it expects 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 no need to type the colons as it already there in the required position.

Below 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 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 accept rule. Say for example, the character 0 states that it only accepts the number. OK. What if the use types M in the placeholder for 0? The input is not accepted. What is Optional and Required? When we type a wrong character in the placeholder the keyed-in character is skipped. This may make you think that you cannot move to next character until the required characters are filled. Right?

But, this is not how the control behaves. You can still the skip the required placeholder and take the output from the masked edit control. Then how the control responds 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.

Below 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 below 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. Below 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





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 shows only when we set focus to the control. Below 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 make changes to the Masked edit control is shown in the below video.

Video





5. Beep on Error

The BeepOnError property makes a bell sound if PC sounds only available. If you have proper sound card then it plays sound file (.Wav) for the error. You can set a different error sound in the control panel for sound option. Below is 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 different prompt character to the Masked edit control. In the sample a masked edit control is used to set the promt character. And the mask prperty for the text box is 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. Below is the code that sets different prompt character to the masked text box control by changing it from default 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 want expected by the property PromptChar. Below video shows the above code, PromptChar property in effect.

Video




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 prompt 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. Below 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



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

End.


Source Code : Download


2 comments:

  1. Wouldn't it be critical to explain how to programatically set and get the value outside of any event handler? For example:

    tbMoney.text = "0000" //has mask $__.__
    decimal money = tbMoney.text //need value not text

    ReplyDelete
  2. using maked Textbox in vb.net
    http://geeksprogrammings.blogspot.com/2013/10/maskedtextboxin.NET.html

    ReplyDelete

Leave your comment(s) here.

C++ Articles

DISCLAIMER

The opinions expressed herein are my own personal opinions and do not represent my current or previous employer's view in anyway