Reputation: 155
I'm trying to read all lines of a text file and export only 2 specific lines to a DataGridView. I have most of the code working, however I ran into a problem where the data isn't always on the same line.
I'm using VB.net Here is the code I'm using.
Dim lines() As String = File.ReadAllLines(textfile)
For i As Integer = 0 To lines.Length - 1
If lines(i).Contains("First*") Then
Dim Array1() As String = lines(i).Split("*")
Dim Array2() As String = lines(i + 1).Split("*")
DataGridView1.Rows.Add(Array1(1), Array2(1))
End If
Next
I Need to do something like this, but I'm not sure how.
Dim lines() As String = File.ReadAllLines("C:\People.txt")
For i As Integer = 0 To lines.Length - 1
If lines(i).Contains("First*") Then
Dim Array1() As String = lines(i).Split("*")
End If
If lines(i).Contains("Last*") Then
Dim Array2() As String = lines(i).Split("*")
End If
DataGridView1.Rows.Add(Array1(1), Array2(1))
Next
My DataGridView contains two columns (FirstName, LastName). So what I'm doing is reading all the lines and when it hits a line that starts with "First*" it collects the firstname and normally below that line is the lastname. I've found that the lastname isn't always directly below it so I need to also do a search for a line that contains "Last*" and add both to the DataGridView. I'm trying to just get the first and last name of each person into the DataGridView.
Here's an example of what the textfile might look like.
First*Bob
Last*Dole
Address*12 Way
Zip*00000
First*John
Middle*M
Last*Smith
Address*13 Way
Zip*00000
You can see on the second person I'd get the wrong information. Appreciate any help.
This is the DataGridView result I'm looking for.
FirstName | LastName
----------------------
Bob | Dole
John | Smith
Upvotes: 1
Views: 149
Reputation: 81610
You should only add the row from inside the If-Block for the "Last Name" check, and you also need to store the first name variable from a higher scope than in your example.
This code does not perform error checking:
Dim firstName As String = String.Empty
Dim lastName As String = String.Empty
For Each s As String In File.ReadAllLines("C:\People.txt")
If s.Contains("First*") Then
firstName = s.Split("*")(1)
End If
If s.Contains("Last*") Then
lastName = s.Split("*")(1)
dgv.Rows.Add(firstName, lastName)
End If
Next
Upvotes: 1