Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

hi i am using winforms in vb.net .. i have this for loop which is below basically i am reading the firstline from a textfile there are empty spaces between the text it is returning therefor everywhere, where there is a space i am adding a number.

 

this is working fine but for some reason after reading the last string which the textfile the for loop keeps on going and adding another extra column for me . can someone tell me how i can make the for loop to stop as soon as it at the end of the first line where there is the last string..

 

thanks in advance

  Dim oSR As New StreamReader(strFilePath)

       'GO TO THE TOP OF THE FILE AND GET THE BEGIN
       oSR.BaseStream.Seek(0, SeekOrigin.Begin)

       '''''ADD THE HEADER COLUMNS TO THE DATSET 
       Dim strFieldss As String
       For Each strFields In oSR.ReadLine().Split(strdelimeter)
           If strFields = "" Then
               strFields = i
           End If
           i = i + 1
           oDT.Columns.Add(strFields)

       Next

Posted

What you are trying to accomplish could probably be done in a better way.

 

Did you copy the code, because the declaration of your variable is spelled strFieldss, whereas your using strFields.

 

  Dim strFieldss As String 

 

Where is (the variable) i coming from?

 

Also, you should compare strFields to string.Empty instead of ""

 

Also, this is called boxing...

 

 strFields = i 

 

and is considered a performance no-no.

 

 

Also, the Split function takes a char array, so naming the parameter strDelimiter is misleading.

 

 For Each strFields In oSR.ReadLine().Split(strdelimeter) 

 

Also, Im sure you know, but your code only reads one line from the file...

if you want to read the whole file, just surround the for next loop with

 

while (oSR.Read())

 

end while

 

 

Now, to the actual problem...

 

The extra column it's adding, Im assuming is a number? The only way I can see that an extra column would be added if there were spaces after the last word on the first line. The [easiest], and Im assuming you want the easiest solution is this

 

   For Each strFields In oSR.ReadLine().Trim().Split(strDelimiter)  

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...