Error: Index was outside the bounds of the array

pwrhngry

New member
Joined
Sep 19, 2005
Messages
2
Programming Experience
Beginner
Hi Everyone,

Just want to thank everyone on this forum. I am pretty much a noob when it comes to any kind of programming and even doing the simplest things seems to be a struggle. I like a challenge though and I like to make things work but I have been fighting with this one for nearly a week now and I am sure it is something simple that I am forgetting to do.

Here is the scenario:
I have a comma delimited .csv file that I want to rearrange and convert into a very simple html page. I am not having a problem setting up the page and I dont seem to be having a problem reading the file however Splitting it into the correct arrays seems to give me this error:

Error: Index was outside the bounds of the array

Here is my code so far ( I know its rudimentary but I wanted to make this work before making it look more elegant and adding bells and whistles. Like I said Im very new)

VB.NET:
Dim Writer As StreamWriter 
Dim Reader As StreamReader
Dim readcontents As String
Dim Textdelimiter As Char
Dim splitout = Split(readcontents, ",")
 
Writer = New StreamWriter("C:\ptc.html")
Writer.Write("<html><head><STYLE TYPE=text/css>")
Writer.Write("td { font-family: verdana; font-size: 8pt; }</STYLE></head><body>")
Writer.Write("<center>")
Writer.Write("<table border=1 cellspacing=0>")
Writer.Write("<tr>")
Writer.Write("<td width=200><B>Customer ID</td><TD width=175><B>Purchase Date</TD><TD width=250><B>Name</TD><TD width=300><B>Expiration / Memo</TD></tr>")
 
Reader = New StreamReader("c:\ptc.csv")
While Reader.Peek <> -1
readcontents = Reader.ReadLine
Writer.WriteLine("<tr><td>" & splitout(0) & "</td><td>" & splitout(1) & "</td><td>" & splitout(2) & "</td><td>" & splitout(3) & "</tr>")
End While
 
Writer.WriteLine("</center>")
Writer.WriteLine("</body></html>")
 
Reader.Close()
Writer.Close()

This seems to be the line that is giving me a problem:
VB.NET:
Writer.WriteLine("<tr><td>" & splitout(0) & "</td><td>" & splitout(1) & "</td><td>" & splitout(2) & "</td><td>" & splitout(3) & "</tr>")

If anyone can steer me in the right direction I would really appreciate it. Thanks!

Pwrhngry
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,553
Location
Sydney, Australia
Programming Experience
10+
You're referring to elements at indices 0, 1, 2 and 3. The error is telling you that at least one of those indices is outside the bounds of the array, i.e. the array doesn't have that many elements. Put a breakpoint on that line and use the Watch window to see what splitout contains.

The real issue is that you are creating splitout before the readcontents variable contains anything. You are reading a line from the file into the readcontents variable within the While loop, so you must also call Split within the loop, after the line has been read.
 
Top Bottom