Results 1 to 32 of 32

Thread: reading a text file and assigning to an array

  1. #1

    Thread Starter
    Member
    Join Date
    Oct 2002
    Posts
    60

    reading a text file and assigning to an array

    I have a text file that has lines that look like this:

    001,Mickey Mouse ,5000,200

    The first is a string and is 3 characters
    The second is a string and fixed at 25 characters
    The last two are singles

    I know how to open the file and read the lines, but how can I separate the values that are text delimited and put them into an array? I know I need a loop to do this, and probably an integer variable to hold the number of records in the array.

    I also need to display the ID numbers (first 3 chars) in list box... how?

    Thanks!

  2. #2
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Actually it might be easier to just split them:
    VB Code:
    1. dim parts() as String=LineStr.Split(",")
    2. Msgbox(parts(0)) 'will show 001
    3. Msgbox(parts(1)) 'will show Mickey Mouse

  3. #3

    Thread Starter
    Member
    Join Date
    Oct 2002
    Posts
    60
    I'm confused....

    Here is what I need to do:
    Write the code necessary to open the input file and read the contents of the file into the form-level array of strings. You will need a loop to do this (you may want to count the number of records in the file in this loop). Also, as you read the records add the ID numbers to the ID List Box Control (you will have to use string manipulation method(s) to obtain this data).

    And here is all I have. I don't understand how to split the line and assign it to the next spot in the array.

    VB Code:
    1. 'open the text file
    2.             Dim objStreamReader As System.IO.StreamReader
    3.             objStreamReader = System.IO.File.OpenText("customers.txt")
    4.             strIDNumbers(intRecordNumber) = objStreamReader.ReadLine()
    5.  
    6.             'customers.txt does not exist, stop
    7.         Else
    8.             MessageBox.Show("File does not exist!", "File not found", _
    9.             MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    10.         End If

  4. #4
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Is this school work or something? What does each line have to be in, an Array of what?

    The code I gave breaks up each line into the individual parts, which is what I thought you meant.

  5. #5

    Thread Starter
    Member
    Join Date
    Oct 2002
    Posts
    60
    Kindof school work. Self taught more like. Ultimately I need to display the comma separated values in labels. So I need to assign each chunk of the line to an array. Then the ID number will be placed in a list box. When you click on the list box, it displays the values of the line in the labels. Make sense?

  6. #6
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Yes but how are you storing each line? In a class? Another Array? What?

    I would suggest a class if you haven't decided already.

    See you need something to hold all the info for a given line and then put each of those in an array or collection for each line. Then bind it to the listbox.

    So your class maybe something like this:
    VB Code:
    1. Public Class Entry
    2.  
    3.   'these should be properties but I'm lazy and just giving an example
    4.   Public ID as String
    5.   Public Name as String
    6.   Public SomeNumber As Single
    7.   Public SomeOtherNumber As Single
    8. End Class

    You would have 1 of those for each line in the file and an array or collection of them for the whole file.

  7. #7

    Thread Starter
    Member
    Join Date
    Oct 2002
    Posts
    60
    I'm getting more confused each time I post... I'm not wondering if I'm even on the right track.

    Basically, I need to take the IDs (the first three characters of each line in the file) and list them in a listbox. When you click on an ID, the values of that line are displayed in a label.

    I'm sorry I've been so confusing.
    Last edited by andrew104; Dec 12th, 2002 at 03:25 AM.

  8. #8
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Ok lets say that you open the file get all the IDs then list them in the listbox. When an Item in the listbox is clicked where do you plan on getting the rest of the data for that line to show in the labels?

  9. #9

    Thread Starter
    Member
    Join Date
    Oct 2002
    Posts
    60
    I have a SelectedValueChanged procedure for the IDListBox. When an item is selected, that ID is looked up in the string array, and the other values are displayed in the labels.

  10. #10
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    The string array will hold the string for the whole line?

    Will you have a string array for each value (seperated by a comma) in the line? Like one to array holds "Mickey Mouse" another "200" and so on?

  11. #11

    Thread Starter
    Member
    Join Date
    Oct 2002
    Posts
    60
    I think it would be best to have each line be a subscript of the array. The text file is fixed at 3 characters for ID number, 25 for name, and then the two numbers will be "single"s, so when the ID is clicked in the listbox, it takes that subscript of the array and displays characters 1-3 in IDLabel, 4-28 in NameLabel, etc... Does that make sense? I think that would work, I'm just not sure how to code it.

  12. #12
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Ok so then in your string array the data would like like:
    VB Code:
    1. Msgbox (strArray(0)) '001,Mickey Mouse ,5000,200
    And you wouldn't actually parse it until it was selected in the listbox?

    If thats the case then you just need to add each line from the file into the array. You can loop through each character of the string finding the "," with the IndexOf Or SubString methods or you can use the Split function.

    What the split function does is take a delimited string and turn it into an array of the parts (the strings between the delimiters). So if you had the following string:

    '001,Mickey Mouse ,5000,200

    And split it then you'd have an array with each element holding the different parts...
    (0)=001
    (1)=Mickey Mouse
    (2)=5000
    (3)=200

    Try this:
    VB Code:
    1. dim SampleStr as String="001,Mickey Mouse ,5000,200"
    2. dim parts() as String=SampleStr.Split(",")
    3. Msgbox(parts(0))
    4. Msgbox(parts(1))
    5. Msgbox(parts(2))
    6. Msgbox(parts(3))

  13. #13
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Thats a lot easier then looping or SubStringing the different lengths.

    If you wanted it to be really easy you could use a class for each line instead, but I don't want to get more confusing.
    Last edited by Edneeis; Mar 23rd, 2005 at 02:21 AM.

  14. #14

    Thread Starter
    Member
    Join Date
    Oct 2002
    Posts
    60
    That's correct. Can you help me with the code for displaying the ID in the listbox, and then how to parse it exactly?

  15. #15
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Do you want to learn a little something about classes to make life easier?

  16. #16
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Instead of using a string array we are going to make a class for the lines. Have you ever made a class before?

  17. #17

    Thread Starter
    Member
    Join Date
    Oct 2002
    Posts
    60
    Sure, if it will help me get this thing working! I appreciate all your help btw.

  18. #18

    Thread Starter
    Member
    Join Date
    Oct 2002
    Posts
    60
    I've never used classes. Is it going to make the code easier? I'm very new to VB.

  19. #19
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Ok I'll explain everything for you. First do you see how on the code page the form is actually a class? See how it starts with Public Class Form1 (or whatever the form name is) and then ends with End Class and all the other code is inbetween (which is a lot). Well to make our own class we will do something like that.

    Go to the project menu and click 'Add Class...'
    Call the file Entry.vb at the prompt.

    No it has the very basic structure of the class:

    Public Class Entry

    End Class

  20. #20
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    For the sake of quickness think of a class as a control without a graphical interface.

    So now we have a class we need to give it some properties. So add the following inside the class:

    VB Code:
    1. Private _ID As String
    2.     Private _Name As String
    3.     Private _Number1 As Single
    4.     Private _Nubmer2 As Single

    These variables will hold the internal values for the properties. Now we add the properties themselves. This should be below the Private variables but still inside the class.

    VB Code:
    1. Public Property ID() As String
    2.         Get
    3.             Return _ID
    4.         End Get
    5.         Set(ByVal Value As String)
    6.             _ID = Value
    7.         End Set
    8.     End Property
    9.  
    10.     Public Property Name() As String
    11.         Get
    12.             Return _Name
    13.         End Get
    14.         Set(ByVal Value As String)
    15.             _Name = Value
    16.         End Set
    17.     End Property
    18.  
    19.     Public Property Number1() As String
    20.         Get
    21.             Return _Number1
    22.         End Get
    23.         Set(ByVal Value As String)
    24.             _Number1 = Value
    25.         End Set
    26.     End Property
    27.  
    28.     Public Property Number2() As String
    29.         Get
    30.             Return _Number2
    31.         End Get
    32.         Set(ByVal Value As String)
    33.             _Number2 = Value
    34.         End Set
    35.     End Property

  21. #21
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Now the last thing we need is the constructor. A constructor is the method that allows you to pass things into the class upon creation and handles creating the actual object. You notice some controls or objects in the framework can take things during the New() part that is the constructor that sets that up.

    So we are going to add a simple constructor that just lets use make an instance of our class like this

    dim cls as New Entry()

    and another one that is going to parse the string line for us

    so add this to the class also:

    VB Code:
    1. Public Sub New()
    2.         MyBase.new()
    3.     End Sub
    4.  
    5.     Public Sub New(ByVal line As String)
    6.         Dim parts() As String = line.Split(",")
    7.         _ID = parts(0)
    8.         _Name = parts(1)
    9.         _Number1 = CType(parts(2), Single)
    10.         _Number2 = CType(parts(3), Single)
    11.     End Sub

    Then we are done with our class and on to the next part. ARe you with me so far?

  22. #22

    Thread Starter
    Member
    Join Date
    Oct 2002
    Posts
    60
    I hate to say this after all the work you did, but I'm not with you. I don't think I'm ready for that. I'm gonna have to stick to the array. Thank you for trying, I'm just not catching on to all of this that well. Makes me feel pretty dumb too.

  23. #23
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Ok I understand, and actually it kind of works out because its almost 2 am here and I gotta work tomorrow. So I'm headed to bed.

    Here is what I would do to get the text into an array:
    VB Code:
    1. 'open the text file
    2.          Dim al As New ArrayList()
    3.         Dim fs As New System.IO.FileStream("customers.txt", IO.FileMode.Open)
    4.         Dim sr As New System.IO.StreamReader(fs)
    5.         Do While sr.Read
    6.             al.Add(sr.ReadLine)
    7.         Loop
    8.         'the lines array now contains the all the lines of text from the text file
    9.         Dim Lines() As String = al.ToArray(GetType(String))
    10.  
    11.             'customers.txt does not exist, stop
    12.         Else
    13.             MessageBox.Show("File does not exist!", "File not found", _
    14.             MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    15.         End If

  24. #24

    Thread Starter
    Member
    Join Date
    Oct 2002
    Posts
    60
    al.Add(sr.ReadLine) doesn't work, Add is not a member of System.Array. How can I fix that? Thanks again.

  25. #25
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Thats fine al is an ArrayList not an array which does have an Add method. Sorry I forgot to put the full namespace, I'm use to the default Imports its System.Collections.ArrayList.

  26. #26
    Lively Member
    Join Date
    Jul 2003
    Posts
    93
    Edneeis,

    That was such a great explaination ....... up until the part when andrew104 changed his mind and went with the array. Is there any way you could finish the example that you started with the class? I'm trying to read in a .txt file and then parse it out to fill fields in a table.

    TIA

    Corinne

  27. #27
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Most of what I previously wrote should apply. Does the text file make just one item or a list of items? Also if you are not constrained to a text file then you should convert to XML and serialization.

    Also this may get more traffic if you start a new thread and just link back to this one.

  28. #28
    Lively Member
    Join Date
    Jul 2003
    Posts
    93
    The text file creates a list of items. I am constrained to a text file at this point.

    If I follow your previous example with creating the class what would be my next step from where you left off without going with the array? Thanks so much for your help, the beginning of your example was great and I'm just hoping that you can complete it for me.

    Thanks again,
    Corinne

  29. #29
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    I had to reread my previous posts to see. The next step would be making a controller or builder class that opens the files and makes all the entry objects. Actually for the sake of space I'll just add it as a shared method of the entry class:
    VB Code:
    1. Public Class Entry
    2.  
    3.     Private _ID As String
    4.     Private _Name As String
    5.     Private _Number1 As Single
    6.     Private _Number2 As Single
    7.  
    8.     Public Property ID() As String
    9.         Get
    10.             Return _ID
    11.         End Get
    12.         Set(ByVal Value As String)
    13.             _ID = Value
    14.         End Set
    15.     End Property
    16.  
    17.     Public Property Name() As String
    18.         Get
    19.             Return _Name
    20.         End Get
    21.         Set(ByVal Value As String)
    22.             _Name = Value
    23.         End Set
    24.     End Property
    25.  
    26.     Public Property Number1() As Single
    27.         Get
    28.             Return _Number1
    29.         End Get
    30.         Set(ByVal Value As Single)
    31.             _Number1 = Value
    32.         End Set
    33.     End Property
    34.  
    35.     Public Property Number2() As Single
    36.         Get
    37.             Return _Number2
    38.         End Get
    39.         Set(ByVal Value As Single)
    40.             _Number2 = Value
    41.         End Set
    42.     End Property
    43.  
    44.     Public Sub New()
    45.         MyBase.new()
    46.     End Sub
    47.  
    48.     Public Shared Function Parse(ByVal line As String) As Entry
    49.         'I switched the constructor to a shared parse method
    50.         'which seemed better since it is really just a parser anyway
    51.         Try
    52.             Dim parts() As String = line.Split(Char.Parse(","))
    53.             Dim newEntry As New Entry
    54.             newEntry.ID = parts(0)
    55.             newEntry.Name = parts(1)
    56.             newEntry.Number1 = CType(parts(2), Single)
    57.             newEntry.Number2 = CType(parts(3), Single)
    58.             Return newEntry
    59.         Catch ex As Exception
    60.             Throw New ArgumentException("Invalid data!")
    61.         End Try
    62.     End Function
    63.  
    64.     Public Shared Function GetEntriesFromFile(ByVal filepath As String) As Entry()
    65.         Dim fs As New IO.FileStream(filepath, IO.FileMode.Open)
    66.         Dim sr As New IO.StreamReader(fs)
    67.         'temp storage for results
    68.         Dim al As New ArrayList
    69.         Do While sr.Peek > 0
    70.             'make an entry object for every line
    71.             Dim item As Entry = Entry.Parse(sr.ReadLine)
    72.             al.Add(item)
    73.         Loop
    74.         fs.Close()
    75.         'convert back to a regular array of entry objects
    76.         Return CType(al.ToArray(GetType(Entry)), Entry())
    77.     End Function
    78.  
    79. End Class
    80.  
    81. 'syntax
    82.         ListBox1.DisplayMember = "Name"
    83.         ListBox1.DataSource = Entry.GetEntriesFromFile("data.txt")

  30. #30
    PowerPoster
    Join Date
    Dec 2003
    Location
    Bristol, England (but heart is in Virginia)
    Posts
    2,949
    Hi Edneeis,

    I concur with Corinne's appreciation of your work of art

    Wouldn't Andrew104's best alternative approach be to use a multi dimension array? I don't know if you can Split the strings directly into multidimensions, but he can easily take the single dimension array containing the split string and transfer the values into the multidimension array.
    This will allow him to display the correct values in his listbox.
    Taxes
    The more I learn about VB.NET the more I like dBaseIII Plus

    The foregoing, whilst believed to be correct, is given without guarantee as to it's accuracy and entirely without recourse. You are required to decide for yourself whether or not it is suitable for your purposes and no liability for loss of any nature can be entertained.

  31. #31
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    I'm not a fan of mutlidimensional arrays myself. They are cumbersome to work with and most functions are more equiped to handle single dimensioned arrays. So personally I'd rather work with an array of a structure or class that represents the data. Also I don't believe you can split directly to a multidimensional array (although I've been wrong before). I'm also not sure which value would display if the items are a multidimensional array where as with an object you can set the DisplayMember to a property or override the ToString method to have some control over what is displayed. Having said all that you could probably get a multidimensional array to work though.

  32. #32
    Lively Member
    Join Date
    Jul 2003
    Posts
    93
    Endeeis,

    Thank you so much for finishing the example. I'm in the process of applying it so hopefully I won't have any more questions.

    Corinne

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