|
-
Dec 12th, 2002, 01:40 AM
#1
Thread Starter
Member
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!
-
Dec 12th, 2002, 02:01 AM
#2
Actually it might be easier to just split them:
VB Code:
dim parts() as String=LineStr.Split(",")
Msgbox(parts(0)) 'will show 001
Msgbox(parts(1)) 'will show Mickey Mouse
-
Dec 12th, 2002, 02:27 AM
#3
Thread Starter
Member
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:
'open the text file
Dim objStreamReader As System.IO.StreamReader
objStreamReader = System.IO.File.OpenText("customers.txt")
strIDNumbers(intRecordNumber) = objStreamReader.ReadLine()
'customers.txt does not exist, stop
Else
MessageBox.Show("File does not exist!", "File not found", _
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
-
Dec 12th, 2002, 02:34 AM
#4
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.
-
Dec 12th, 2002, 02:47 AM
#5
Thread Starter
Member
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?
-
Dec 12th, 2002, 02:55 AM
#6
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:
Public Class Entry
'these should be properties but I'm lazy and just giving an example
Public ID as String
Public Name as String
Public SomeNumber As Single
Public SomeOtherNumber As Single
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.
-
Dec 12th, 2002, 03:14 AM
#7
Thread Starter
Member
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.
-
Dec 12th, 2002, 03:28 AM
#8
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?
-
Dec 12th, 2002, 03:33 AM
#9
Thread Starter
Member
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.
-
Dec 12th, 2002, 03:38 AM
#10
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?
-
Dec 12th, 2002, 03:43 AM
#11
Thread Starter
Member
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.
-
Dec 12th, 2002, 03:51 AM
#12
Ok so then in your string array the data would like like:
VB Code:
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:
dim SampleStr as String="001,Mickey Mouse ,5000,200"
dim parts() as String=SampleStr.Split(",")
Msgbox(parts(0))
Msgbox(parts(1))
Msgbox(parts(2))
Msgbox(parts(3))
-
Dec 12th, 2002, 03:53 AM
#13
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.
-
Dec 12th, 2002, 04:05 AM
#14
Thread Starter
Member
That's correct. Can you help me with the code for displaying the ID in the listbox, and then how to parse it exactly?
-
Dec 12th, 2002, 04:09 AM
#15
Do you want to learn a little something about classes to make life easier?
-
Dec 12th, 2002, 04:12 AM
#16
Instead of using a string array we are going to make a class for the lines. Have you ever made a class before?
-
Dec 12th, 2002, 04:13 AM
#17
Thread Starter
Member
Sure, if it will help me get this thing working! I appreciate all your help btw.
-
Dec 12th, 2002, 04:15 AM
#18
Thread Starter
Member
I've never used classes. Is it going to make the code easier? I'm very new to VB.
-
Dec 12th, 2002, 04:18 AM
#19
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
-
Dec 12th, 2002, 04:23 AM
#20
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:
Private _ID As String
Private _Name As String
Private _Number1 As Single
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:
Public Property ID() As String
Get
Return _ID
End Get
Set(ByVal Value As String)
_ID = Value
End Set
End Property
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal Value As String)
_Name = Value
End Set
End Property
Public Property Number1() As String
Get
Return _Number1
End Get
Set(ByVal Value As String)
_Number1 = Value
End Set
End Property
Public Property Number2() As String
Get
Return _Number2
End Get
Set(ByVal Value As String)
_Number2 = Value
End Set
End Property
-
Dec 12th, 2002, 04:28 AM
#21
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:
Public Sub New()
MyBase.new()
End Sub
Public Sub New(ByVal line As String)
Dim parts() As String = line.Split(",")
_ID = parts(0)
_Name = parts(1)
_Number1 = CType(parts(2), Single)
_Number2 = CType(parts(3), Single)
End Sub
Then we are done with our class and on to the next part. ARe you with me so far?
-
Dec 12th, 2002, 04:39 AM
#22
Thread Starter
Member
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.
-
Dec 12th, 2002, 04:49 AM
#23
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:
'open the text file
Dim al As New ArrayList()
Dim fs As New System.IO.FileStream("customers.txt", IO.FileMode.Open)
Dim sr As New System.IO.StreamReader(fs)
Do While sr.Read
al.Add(sr.ReadLine)
Loop
'the lines array now contains the all the lines of text from the text file
Dim Lines() As String = al.ToArray(GetType(String))
'customers.txt does not exist, stop
Else
MessageBox.Show("File does not exist!", "File not found", _
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
-
Dec 12th, 2002, 05:01 AM
#24
Thread Starter
Member
al.Add(sr.ReadLine) doesn't work, Add is not a member of System.Array. How can I fix that? Thanks again.
-
Dec 12th, 2002, 11:15 AM
#25
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.
-
Feb 25th, 2004, 04:48 PM
#26
Lively Member
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
-
Feb 25th, 2004, 05:31 PM
#27
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.
-
Feb 26th, 2004, 09:06 AM
#28
Lively Member
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
-
Feb 26th, 2004, 11:26 AM
#29
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:
Public Class Entry
Private _ID As String
Private _Name As String
Private _Number1 As Single
Private _Number2 As Single
Public Property ID() As String
Get
Return _ID
End Get
Set(ByVal Value As String)
_ID = Value
End Set
End Property
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal Value As String)
_Name = Value
End Set
End Property
Public Property Number1() As Single
Get
Return _Number1
End Get
Set(ByVal Value As Single)
_Number1 = Value
End Set
End Property
Public Property Number2() As Single
Get
Return _Number2
End Get
Set(ByVal Value As Single)
_Number2 = Value
End Set
End Property
Public Sub New()
MyBase.new()
End Sub
Public Shared Function Parse(ByVal line As String) As Entry
'I switched the constructor to a shared parse method
'which seemed better since it is really just a parser anyway
Try
Dim parts() As String = line.Split(Char.Parse(","))
Dim newEntry As New Entry
newEntry.ID = parts(0)
newEntry.Name = parts(1)
newEntry.Number1 = CType(parts(2), Single)
newEntry.Number2 = CType(parts(3), Single)
Return newEntry
Catch ex As Exception
Throw New ArgumentException("Invalid data!")
End Try
End Function
Public Shared Function GetEntriesFromFile(ByVal filepath As String) As Entry()
Dim fs As New IO.FileStream(filepath, IO.FileMode.Open)
Dim sr As New IO.StreamReader(fs)
'temp storage for results
Dim al As New ArrayList
Do While sr.Peek > 0
'make an entry object for every line
Dim item As Entry = Entry.Parse(sr.ReadLine)
al.Add(item)
Loop
fs.Close()
'convert back to a regular array of entry objects
Return CType(al.ToArray(GetType(Entry)), Entry())
End Function
End Class
'syntax
ListBox1.DisplayMember = "Name"
ListBox1.DataSource = Entry.GetEntriesFromFile("data.txt")
-
Feb 26th, 2004, 12:15 PM
#30
PowerPoster
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.
-
Feb 26th, 2004, 12:51 PM
#31
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.
-
Feb 26th, 2004, 04:29 PM
#32
Lively Member
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|