Search code examples
vb.netmaskedtextbox

Check Masked Text Box is empty or not VB.NET


I have Masked Text Boxes in my form. One is for salary, PF&ESI and Other is for Phone Number. I try to check the Masked Text Box is empty or not with following code.

Dim mtxt As Control
Dim flag3 As Boolean
flag3 = False
For Each mtxt In EMPGBDATA.Controls
    If TypeOf mtxt Is MaskedTextBox  Then
        If mtxt.Text = "" Then
            mtxt.BackColor = Color.Red
            flag3 = True
        End If
    End If
Next 

Only my salary, PF&ESI Masked Text Box show in Red color, But Phone number Masked Text Box is not show Red.


Solution

  • I think you have the following situation: (Probably defined by the property designer)

     maskedTextBoxPhoneNumber.Mask = "000000 00000"  'Or something similar'
     maskedTextBoxPhoneNumber.TextMaskFormat = MaskFormat.IncludeLiterals 
    

    in this case your test for

     if mtxt.Text = "" then 
    

    will fail because the literals included in the mask property are returned in the property Text

    you should change the property TextMaskFormat to

     maskedTextBoxPhoneNumber.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals
    

    See MSDN for MaskFormat Enumeration