Search code examples
vb.netdatagrid

Bound datagrid not showing values


I have a datagrid which is bound to a binding source which itself is populated from a list.

I can see that the binding source is populated and I can see that the datagrid has the expected number of rows to match the data in the list but i can not get the columns to populate with the data. I have tried setting the datapropertyname for the columns but to no avail. I know this is probably dead simple but I'm going round in circles.

Please can anyone help

Dim cE As New ClsEmail

    Dim bs As New BindingSource
    Dim dgv = Me.DataGridView1

    dgv.AutoGenerateColumns = False

    bs.DataSource = cE.GetMail("[email protected]")

    With dgv.Columns(0)
        .DataPropertyName = "ID"
        .HeaderText = "ID"

    End With

    With dgv.Columns(1)
        .DataPropertyName = "Subject"
        .HeaderText = "Subject"
    End With

    dgv.DataSource = bs

When i press the button to populate the datagrid I get four rows but no values in the columns. Clearly I'm not binding the columns correctly but i can't see what I'm missing.


Solution

  • List(Of T) is already bindable. Rearrange your properties in your Email class like this, as the DataGridView will create the columns in property order:

    Public Class Email 
    
        Public Property ID As Integer
        Public Property Subject As String 
        Public Property DateReceived As DateTime 
    
    End Class
    

    Then, just set the datasource like this:

    With DataGridView1
    
        .AutoGenerateColumns = True
        .DataSource = cE.GetMail("[email protected]")
        .Columns(2).Visible = False ' DataReceived (if you really intended to hide this)
    
    End With