1

I'm new to VB.net and I don't know how to display certain columns and rows in datagridview that was imported from CSV file. My problem is I have many columns and all I want to display is 2 columns:

Name,Age,Mobile Number,ID number

Alex,18,09848484841,0010

George,19,02987654321,0020

Toni,17,09277470257,0030

How can I display only the Name & Age columns and its rows?

2 Answers 2

9

If you use a datatable you get the data structure and collection together. something like this:

    Dim sr As New IO.StreamReader(filename)
    Dim dt As New DataTable
    Dim newline() As String = sr.ReadLine.Split(","c)
    dt.Columns.AddRange({New DataColumn(newline(0)), _
                         New DataColumn(newline(1))})
    While (Not sr.EndOfStream)
        newline = sr.ReadLine.Split(","c)
        Dim newrow As DataRow = dt.NewRow
        newrow.ItemArray = {newline(0), newline(1)}
        dt.Rows.Add(newrow)
    End While
    DataGridView1.DataSource = dt
Sign up to request clarification or add additional context in comments.

3 Comments

That's what I'm talking about man! You got it! Thank you. You're the man.
Hey @tinstaff, When im using this code, i got the error of "Index was outside the bounds of the array." in the code newrow.ItemArray = {newline(0), newline(1)}
@Aljie, If the line that readline reads, doesn't have at least 2 fields separated by a comma then the newline array won't have enough indexes. You might need a conditional to check if newline's length is at least 2. Sometimes a file will have empty lines in it. This can also happen if the data isn't strongly validated before it's written to the file.
0

Use a custom class with properties that match the data you want to store and make an instance of that class for each row of data use read, then have a List(Of {custom class}) to hold each object and the DGV's DataSource property can view the collection in the grid. The property names in the class will be used as the header.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.