Using an If statement when comparing two variables

ABOU

Member
Joined
Apr 29, 2008
Messages
14
Programming Experience
Beginner
I am trying to assign validation to a text box, SexTextBox

I wish to allow only M or F to be inserted, if the user inserts anything else i want it to throw up an error provider.

So far i have come up with:

VB.NET:
If Me.SexTextBox.Text <> "M" Then
            Me.ErrorProvider1.SetError(SexTextBox, "Enter M or F only!")
            Me.SexTextBox.Text = ""
            Me.SexTextBox.Focus()
        Else
            Me.ErrorProvider1.SetError(SexTextBox, "")

        End If

This will work to prevent all but M being entered.

I thought that if i wanted to allow M and F creating the following code would work:

VB.NET:
If Me.SexTextBox.Text = "M" Then
            Me.ErrorProvider1.SetError(SexTextBox, "")


        ElseIf Me.SexTextBox.Text = "F" Then
            Me.ErrorProvider1.SetError(SexTextBox, "")

        Else

            Me.ErrorProvider1.SetError(SexTextBox, "Enter M or F only!")
            Me.SexTextBox.Text = ""
            Me.SexTextBox.Focus()

        End If

It appears to prevent incorrect entry but no error provider is displayed.


Found this forum post seems to explain it:

http://www.developerfusion.co.uk/forums/p/36104/149689/#149689

 
Last edited:
This sounds like a web form, but I could be wrong.

Why don't you use a ComboBox. Let them select the word "Male" or "Female" with "Male" having a value of "M" and "Female" has a value of "F".

But this code here should do the trick for ya:
VB.NET:
        If Me.SexTextBox.Text <> "M" AndAlso Me.SexTextBox.Text <> "F" Then
            Me.ErrorProvider1.SetError(SexTextBox, "Enter M or F only!")
            Me.SexTextBox.Text = ""
            Me.SexTextBox.Focus()
        Else
            Me.ErrorProvider1.SetError(SexTextBox, "")
        End If
 
IT hadnt occured to me to use a combo box, as it is for an assignemnt i wanted to make use of as many components as i can.

I have never come across the
VB.NET:
AndAlso
expression, was racking my brains over that today.
 
AndAlso is new to VB .Net and is actually better to use in the sense that AndAlso doesn't evaluate both cases all the time, if the first case fails VB never bothers with the second (third, fourth, etc) because the whole thing will be false if any one of them are false.

This speeds things up quite a bit, especially in the middle of loops.
 
I know it may be obvious, but I'll state it anyway :D - there's also "OrElse" :)
 
Back
Top