Make sure that the maximum index of a list is less than its size

Hb_Kai

Member
Joined
Dec 1, 2008
Messages
10
Programming Experience
Beginner
I'm only learning right now and what I'm trying to do is to test a TextBox text to see if the user has entered a valid email address (if contains @ symbol)

So far I've got things right, but somehow I'm getting the error message "Make sure that the maximum index of a list is less than its size" and I don't know where I've gone wrong. :(

This is the code I'm using for this...

VB.NET:
        Dim email As String
        Dim counter As Integer


        email = Trim(TextBox2.Text)

        For i = 0 To email.Length
            If email.Chars(i) = "@" Then    !The error highlights and points to this line!
                counter = counter = 1
            End If
        Next i

        If counter = 1 Then
            MsgBox("Thank you for your email address")
        ElseIf counter > 1 Then
            MsgBox("Enter a valid email addres")
        End If

Where am I going wrong? :(
 
Look at this line:
VB.NET:
For i = 0 To email.Length
Let's assume that there are 10 characters in your string. That loop is going to loop from 0 to 10. That's 11 iterations, which is a problem if there are only 10 characters. If the first index is 0 rather than 1, what does that mean for the last index?
 
Doesn't the count start at 0? If it does, would it mean that the count can only fit the first character in and can't loop the rest of the email address?
 
10 elements starting at 1

1 2 3 4 5 6 7 8 9 10

10 elements starting at 0

0 1 2 3 4 5 6 7 8 9

So if your length is 10 and you're starting at 0...

VB.NET:
For i = 0 To email.Length - 1

Jmcilhinney was trying to get you to come to this conclusion on your own.
 
I thought that already but wasn't sure. Think I worded the reply wrong too. :S

I tried using that in the code anyway but nothing happened when I clicked the button. :S
 
You know, youre writing an awful lot of code to achieve something Microsoft already did:

VB.NET:
If txtEmailAddress.Text.Contains("@") Then
  'thanks for your email address
Else
  'please provide an email address
End If

ps; when you drop a textbox on a form, and the forms designer names it TextBox2.. youre supposed to rename it to something meaningful ;)
 
MailAddress class (System.Net.Mail) can also be used for simple validation of the address string, slightly better than checking for a "@".
 
Back
Top