简体   繁体   中英

How To Read Text File to Datagridview

I've a project that I want to load text file to a DataGridview .
Data :

"#Tools Must You Have  
Tool_1 Screwdriver T1    
Tool_2 Screw T2   
Tool_3 Ruler T3" 

I have two button( btSave & btOpen ) and a DataGridview has two columns( Tools & Name )
i want to read the data to DataGridview , but I want skipping the line beginning with " # "

I tried it with this code

Private Sub LoadGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
    ThisGrid.Rows.Clear()
    Dim TextLine As String = ""
    Dim SplitLine() As String
    Using objReader As New System.IO.StreamReader(Filename)
        Do While objReader.Peek() <> -1
            TextLine = objReader.ReadLine()
            SplitLine = Split(TextLine, " ")
            Me.DataGridView1.Rows.Add(SplitLine)
        Loop
    End Using
End Sub

This code is wrong, when it's loaded, text in column is not same, only read one word " Screwdriver " not " screwdriver T1 ",
any solution for this ?

Private Sub LoadGridData(ByVal ThisGrid As DataGridView, ByVal Filename As String)
    ThisGrid.Rows.Clear()
    ThisGrid.Rows.AddRange( 
        File.ReadLines(FileName).
              Where(Function(line) Not line.TrimStart().StartsWith("#")).
              Select(Function(line) line.Split(" ".ToCharArray(), 2)).
              ToArray() 
     ) 
End Sub

Note (among other things) the change from ByRef to ByVal . It's easy to miss that one, and ByRef vs ByVal probably doesn't mean what you think it does. Remember that ByVal in VB.Net still passes references . The difference is that it makes a copy of the reference value, but since that copy still refers to the same DataGridView object, it will do what you want it to do. The only time you should use ByRef is if you need to make an assignment directly to the variable, and you want that assignment to show up in the calling code. This is different from assigning to a property of the object. You only need this if you want to actually replace the entire object, and that should be almost never.

When you run that split function, you're splitting the entire string on each space so you end up with 3-long array and the T1 is in the third string. I'm assuming your table is defined with two columns only. Try this:

    Do While objReader.Peek() <> -1
        TextLine = objReader.ReadLine()
        If Textline.Trim.Length > 0 AndAlso not TextLine.StartsWith("#") Then
            DataGridView1.Rows.Add(TextLine.Split(" ")(0), textLine.Replace(TextLine.Split(" ")(0), "").Substring(1))
        End If
    Loop

And really, I'm making all kinds of assumptions about your assignment and your data, but this should get you going in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM