Question Using a List of Custom Class as Datasource for Datagridview

Joined
Mar 18, 2014
Messages
18
Location
Devon, UK
Programming Experience
3-5
Hi.

Ok, I must be missing something really simple here.
I have a form with just a Datagridview on it

Why doesn't this work?

Imports System.IO
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim filelist As New List(Of MyFileInfo)
        For Each fi As FileInfo In New DirectoryInfo("D:\").GetFiles
            Dim myfile As New MyFileInfo With {.Name = fi.Name, .FullName = fi.FullName, .Length = fi.Length}
            filelist.Add(myfile)
        Next
        DataGridView1.DataSource = filelist
    End Sub
End Class


Public Class MyFileInfo
    Public Name As String
    Public Length As Long
    Public FullName As String
   
    Public Sub New()
    End Sub
    
    Public Sub New(ByVal Name As String)
        Me.Name = Name
    End Sub
End Class



MyFileInfo is just a class that stores the Name, FullName and Length of the file..... I don't want all of the columns returned that GetFiles() normally kicks out.

If I did DataGridview1.Datasource = New DirectoryInfo("D:\").GetFiles then the datagridview shows all the results alright, but if I try and use MyFileInfo class as a DataSource the DataGridView doesn't show anything back, even though I can see that the DataSource does have values when debugging, it just doesn't show it in the DataGridView control.

Any ideas?

DG
 
Last edited by a moderator:
Firstly, I have fixed the code formatting in your post. When using xcode tags, you must specify "vb" as the option to use VB syntax highlighting.

As for the issue, it's because your type has no properties. Only properties can be bound; not fields. Change your fields to properties and you'll get the result you want. This is just one of the reasons that you should ALWAYS use properties to expose data publicly; never fields.
 
Brilliant! - Thanks ever so much for that.
I do appreciate you taking the time to answer each of my posts jmcilhinney - I do learn a lot from you.

I'm still finding my feet with regards to using these forum tools as well so thanks for altering the post to put it as vb code.

Keep a lookout for my next query.... I'm sure they'll be one coming along real soon :adoration:
 
Back
Top