VB.NET 2010

Is there a way to restrict a Masked Text Box to accept only certain letters? I know how to restrict for all letters. For example, the user should only input the letters "P", "R" or "N" ( or can be blank) in a particular Masked Text Box. I want to accomplish this without using a combo box. In case not,I tried to write an OR statement to test for the proper input but am having trouble.

If (MTXT_BillCode <> "P") Or (MTXT_BillCode <> "R") Or (MTXT_BillCode <> "N") Or (MTXT_BillCode <> " ") Then
                lbl_Message.Text = "Invalid Bill Code -- R,N,P Only"
End If

Thank you very much in advance.

Think MSDN might help you here. Just change the code of the example a bit and it should work for you. Success.

commented: Nice & appropriate supporting. +4

Another way is to use a regular textbox and handle the Validating event:

Private Sub TXT_BillCode_Validating(sender As Object, e As CancelEventArgs) Handles TXT_BillCode.Validating
    Const codes As String = "PNRpnr"
    If TXT_BillCode.Text.Length > 1 OrElse TXT_BillCode.Text <> "" OrElse Not codes.Contains(TXT_BillCode.Text) Then
        MessageBox.Show("Invalid Code", "Please enter only the letters P,N, or R")
        e.Cancel = True
    End If
End Sub
commented: Validation checking also be a good choice. +4

Which event do you use your code in?

If you are only allowed P, R or N then I suggest you use a combobox. Why allow the user to bang on invalid keys? Just show him/her the valid choices.

commented: The right choice indeed! +15

In your masked textbox set your input mask in the properties window to: >L
This allows the input of one character changed to upper case.
Then put the following codes:

 Private Sub MaskedTextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles MaskedTextBox1.KeyDown
        If e.KeyCode = Keys.P Or e.KeyCode = Keys.N Or e.KeyCode = Keys.R Then
            MsgBox("Good imput, proceed with code")
        End If
    End Sub

and also:

Private Sub MaskedTextBox1_KeyUp(sender As Object, e As KeyEventArgs) Handles MaskedTextBox1.KeyUp
        If e.KeyCode <> Keys.P Or e.KeyCode <> Keys.N Or e.KeyCode <> Keys.R Then
            MaskedTextBox1.Text = ""
            MaskedTextBox1.Refresh()
        End If
    End Sub

The code in the key up event will reset the masked textbox in case of wrong input.

I want to accomplish this without using a combo box.

@Triple_7 doesn't want to use combobox. It is in his posting.

commented: The OP does asks about his solution not the best solution. +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.