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.

Edited 1 Year Ago by Triple_7

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

Comments
Nice & appropriate supporting.

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

Edited 1 Year Ago by tinstaafl

Comments
Validation checking also be a good choice.

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.

Comments
The right choice indeed!

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.

Edited 1 Year Ago by Minimalist

I want to accomplish this without using a combo box.

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

Edited 1 Year Ago by Shark_1

Comments
The OP does asks about his solution not the best solution.
This article has been dead for over six months. Start a new discussion instead.