Results 1 to 14 of 14

Thread: Upload Data from Text Files into Arrays

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jun 2011
    Posts
    70

    Upload Data from Text Files into Arrays

    Hi,

    I have text files that are formatted like the following:

    "Title"
    3403203, 3/15/10, "Rebate File", 12
    30392.3, 4/10/09, "Kentucky", 23
    392948.30, 1/12/07, "Water Waste", 15


    I was wondering how to code a button that will get the title in the first line and set it as a variable and then create four arrays (one for each column: number, date, description, number). Thanks for the help! I will gladly rate your posts!

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Upload Data from Text Files into Arrays

    Unless you have to because this is homework, you should not use four separate arrays. You should define a type, i.e. a class or a structure, with four properties, one for each column in the file.

    You can then use a TextFieldParser to read the data. The MSDN documentation has code examples. The only difference is that you would read a single field the first time and multiple fields each time thereafter.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Jun 2011
    Posts
    70

    Re: Upload Data from Text Files into Arrays

    Ok, thanks you. I am unfamiliar with what a class/structure is. Also, part of my confusion is uploading the actual document. How do I go about doing that? Thanks again!

  4. #4
    Master Of Orion ForumAccount's Avatar
    Join Date
    Jan 2009
    Location
    Canada
    Posts
    2,802

    Re: Upload Data from Text Files into Arrays

    You are in way over your head in you don't know these basic concepts. I would suggest MSDN + Google.

  5. #5
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Upload Data from Text Files into Arrays

    I am unfamiliar with what a class/structure is.
    Every type you use (Form, String, Integer, etc) is a class or a structure. When you create a new Windows Forms Application project and it creates a new form for you, notice that the code says:
    vb.net Code:
    1. Public Class Form1
    2.  
    3. End Class
    Your Form1 is a class, and when you write code you are adding members, e.g. properties and methods, to that class. Just as you can add a new form to your project, you can add a new class.
    Also, part of my confusion is uploading the actual document. How do I go about doing that?
    There is no "uploading". Uploading is the process of a client sending data to a server, while downloading is a client getting data from a server. In this case, all you're doing is opening and reading a local file. As for how you do that, I already said:
    You can then use a TextFieldParser to read the data. The MSDN documentation has code examples.
    The implication was that you should read the MSDN documentation for the TextFieldParser class. You don't need any programming experience to be able to use the web:

    http://www.bing.com/search?q=msdn+te...&sk=&form=QBRE
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  6. #6

    Thread Starter
    Lively Member
    Join Date
    Jun 2011
    Posts
    70

    Re: Upload Data from Text Files into Arrays

    Ok thank you very much. Sorry that I'm such a beginner at this. Instead of having the data go into an array, I'm going to have it put into my datagridview called dgv. I've made this code but it keeps giving an error @ the line dgv(0 + j, 0 + i) = currentField saying "Unable to cast object of type 'System.String' to type 'System.Windows.Forms.DataGridViewCell'." Do you know what the problem could be?

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
    Dim File As String
    Dim FileName As String
    Dim currentrow(6) As Object
    Dim i As Integer
    Dim j As Integer

    File = InputBox("Please input the name of the file you wish to upload.", "AMTEC")
    FileName = Convert.ToString("C:\" & File & ".REB")

    If My.Computer.FileSystem.FileExists(FileName) Then
    Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser = _
    My.Computer.FileSystem.OpenTextFieldParser(FileName)
    'Set the reader's TextFieldType to delimited
    reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
    'Set the readers Delimiters to a comma (,)
    reader.Delimiters = New String() {",", vbTab}
    'ignore the lines starting with this token

    j = 0
    Do While Not reader.EndOfData
    Try
    currentrow = reader.ReadFields
    Dim currentField As Object
    i = 0
    For Each currentField In currentrow
    dgv(0 + j, 0 + i) = currentField
    i = i + 1
    Next
    j = j + 1
    Catch ex As Microsoft.VisualBasic.
    FileIO.MalformedLineException
    MsgBox("Line " & ex.Message &
    "is not valid and will be skipped.")
    End Try
    Loop

    reader.Close()
    Else
    MsgBox("Error: File does not exsist!", , "AMTEC")
    End If

    End Sub

  7. #7
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Upload Data from Text Files into Arrays

    First up, what's the point of adding zero to your loop counters? Isn't (0 + j) just equal to j?

    As for the question, you aren't setting a cell in the grid, you're setting the value in that cell. When you index the grid like that you are getting a DataGridViewCell. You should read the MSDN documentation for that class and your question will be answered. You will also find lots of other information on the class and see how easy it is to answer questions from the documentation, both of which will help you in the future.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  8. #8

    Thread Starter
    Lively Member
    Join Date
    Jun 2011
    Posts
    70

    Re: Upload Data from Text Files into Arrays

    Yeah I don't know why I had the zeros there. And thank you for directing me to the MSDN, I figured out my problem. Thanks

  9. #9
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Upload Data from Text Files into Arrays

    Glad it helped.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  10. #10

    Thread Starter
    Lively Member
    Join Date
    Jun 2011
    Posts
    70

    Re: Upload Data from Text Files into Arrays

    Sorry to bother you again jmcilhinney, but I have one error that I just can't figure out. I am using the following code to read lines that are comma delimitted:

    File = InputBox("Please input the name of the file you wish to upload.", "AMTEC")
    FileName = Convert.ToString("C:\" & File & ".txt")

    If My.Computer.FileSystem.FileExists(FileName) Then
    Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser = _
    My.Computer.FileSystem.OpenTextFieldParser(FileName)
    reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
    reader.Delimiters = New String() {","}

    j = 0
    Do While Not reader.EndOfData
    Try
    currentrow = reader.ReadFields

    i = 0
    For Each currentField In currentrow
    If i = 0 Then
    Format(currentField, "MM/dd/yy")
    End If
    dgv(i, j).Value = Convert.ToString(currentField)
    i = i + 1
    dgv.Rows.Add(1)
    Next

    j = j + 1
    Catch ex As Microsoft.VisualBasic.
    FileIO.MalformedLineException
    MsgBox("Line " & ex.Message &
    "is not valid and will be skipped.")
    End Try
    Loop

    reader.Close()
    Else
    MsgBox("Error: File does not exsist!", , "AMTEC")
    End If


    For some reason all of the data is correctly entered into my datagrid except the entry that is supposed to be in in cell (0,0). Instead, it is entered into the last row in the zero column. Thanks.

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Upload Data from Text Files into Arrays

    Please use the Code or VBCode button provided to wrap your code snippets in formatting tags. It's just too hard to read otherwise, mainly because of a lack of indenting.

    On an unrelated note, look at this:
    Code:
    File = InputBox("Please input the name of the file you wish to upload.", "AMTEC")
    FileName = Convert.ToString("C:\" & File & ".txt")
    What's the point of calling Convert.ToString and passing a String? Isn't it already a String? You're using Convert.ToString on another String later on in the code too.

    Also, I strongly recommend against using InputBox for anything at all. In this case, should you not be using an OpenFileDialog? That will allow the user to select from any folder rather than just the root of the C drive, which you should pretty much never place files in anyway. It will also take care of ensuring that they only select a file that exists, which you aren't doing at all at the moment.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  12. #12

    Thread Starter
    Lively Member
    Join Date
    Jun 2011
    Posts
    70

    Re: Upload Data from Text Files into Arrays

    vb Code:
    1. File = InputBox("Please input the name of the file you wish to upload.", "AMTEC")
    2.         FileName = Convert.ToString("C:\" & File & ".txt")
    3.  
    4.         If My.Computer.FileSystem.FileExists(FileName) Then
    5.             Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser = _
    6.             My.Computer.FileSystem.OpenTextFieldParser(FileName)
    7.             reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
    8.             reader.Delimiters = New String() {","}
    9.  
    10.             j = 0
    11.             Do While Not reader.EndOfData
    12.                 Try
    13.                     currentrow = reader.ReadFields
    14.  
    15.                     i = 0
    16.                     For Each currentField In currentrow
    17.                         If i = 0 Then
    18.                             Format(currentField, "MM/dd/yy")
    19.                         End If
    20.                         dgv(i, j).Value = Convert.ToString(currentField)
    21.                         i = i + 1
    22.                         dgv.Rows.Add(1)
    23.                     Next
    24.  
    25.                     j = j + 1
    26.                 Catch ex As Microsoft.VisualBasic.
    27.                             FileIO.MalformedLineException
    28.                     MsgBox("Line " & ex.Message &
    29.                     "is not valid and will be skipped.")
    30.                 End Try
    31.             Loop
    32.  
    33.             reader.Close()
    34.         Else
    35.             MsgBox("Error: File does not exsist!", , "AMTEC")
    36.         End If

  13. #13

    Thread Starter
    Lively Member
    Join Date
    Jun 2011
    Posts
    70

    Re: Upload Data from Text Files into Arrays

    And thank you for the other comments and suggestions. I will fix them now!

  14. #14
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Upload Data from Text Files into Arrays

    I can see now that you are checking that the file exists. That's an example of how things can get lost when code is not formatted. Still, I would think that using an OpenFileDialog would be preferable.

    As for the issue, nothing jumps out but I think that your code is more complex than it needs to be anyway. Using a For Each loop and then maintaining a separate counter doesn't make sense when you can just use a For loop.

    Also, your Format call for the date is useless because the value you pass is not a Date but a String. You can't format a String as a Date because the system has no idea what the day, month and year values are. You have to convert the String to a Date first. Besides that, Format doesn't affect the value you pass in. It passes a new, formatted value out. You aren't using that value so it's of no use regardless. There's no point formatting the data in code anyway. You should just set the format for the column and then add Date values to the column. Here's a simplified example of how I'd do it:
    vb.net Code:
    1. Using reader As New TextFieldParser("file path here")
    2.     Dim rows As New List(Of DataGridViewRow)
    3.  
    4.     Do Until reader.EndOfData
    5.         Dim fields = reader.ReadFields()
    6.         Dim row As New DataGridViewRow
    7.  
    8.         row.CreateCells(Me.DataGridView1)
    9.  
    10.         For columnIndex = 0 To fields.GetUpperBound(0)
    11.             If columnIndex < Me.DataGridView1.ColumnCount Then
    12.                 Dim value As Object = fields(columnIndex)
    13.  
    14.                 If columnIndex = 0 Then
    15.                     Dim dt As Date
    16.  
    17.                     If Date.TryParse(CStr(value), dt) Then
    18.                         value = dt
    19.                     Else
    20.                         value = Nothing
    21.                     End If
    22.                 End If
    23.  
    24.                 row.Cells(columnIndex).Value = value
    25.             End If
    26.         Next
    27.     Loop
    28.  
    29.     Me.DataGridView1.Rows.AddRange(rows.ToArray())
    30. End Using
    Some points to note here:
    1. The file is opened with a Using statement, ensuring that it always gets closed, even if an unhandled exception is thrown.
    2. All the rows are created first and then added in a single batch, which is much faster than adding the rows one by one as they are created.
    3. The first column value is converted to a Date and added to the grid as a Date. The grid column can then do the formatting for you. This has an added advantage that the column can be sorted chronologically. If the data in that column is not a valid date then it is left blank, but you may prefer a different course of action.
    4. The column index of both the data being read and the target grid are taken into account, to ensure that there are no invalid indexes used, e.g. if a source row has more fields than there are columns in the grid.
    If I was really doing this though, what I'd actually do is define a type to represent a record and read the data into a list of instances of that type. I'd then bind that list to the grid. I always prefer to use data-binding unless there's a specific reason not to.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width