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!
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.
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!
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.
Re: Upload Data from Text Files into Arrays
Quote:
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:
Public Class Form1
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.
Quote:
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:
Quote:
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
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
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.
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
Re: Upload Data from Text Files into Arrays
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.
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.
Re: Upload Data from Text Files into Arrays
vb Code:
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
Re: Upload Data from Text Files into Arrays
And thank you for the other comments and suggestions. I will fix them now!
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:
Using reader As New TextFieldParser("file path here")
Dim rows As New List(Of DataGridViewRow)
Do Until reader.EndOfData
Dim fields = reader.ReadFields()
Dim row As New DataGridViewRow
row.CreateCells(Me.DataGridView1)
For columnIndex = 0 To fields.GetUpperBound(0)
If columnIndex < Me.DataGridView1.ColumnCount Then
Dim value As Object = fields(columnIndex)
If columnIndex = 0 Then
Dim dt As Date
If Date.TryParse(CStr(value), dt) Then
value = dt
Else
value = Nothing
End If
End If
row.Cells(columnIndex).Value = value
End If
Next
Loop
Me.DataGridView1.Rows.AddRange(rows.ToArray())
End Using
Some points to note here:- The file is opened with a Using statement, ensuring that it always gets closed, even if an unhandled exception is thrown.
- 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.
- 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.
- 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.