troubleshooting Question

Databound DataGridView not refreshing correctly

Avatar of melance42
melance42 asked on
Visual Basic.NET
4 Comments1 Solution515 ViewsLast Modified:
I have a form that contains a datagridview with it's datasource set to a bindinglist(of T) and several controls.  When a row is selected in the datagridview, I bind that row's DataBoundItem properties to the controls.  When I need a new record, the user clicks an "Add New" button which in turn adds a record the BindingList(of T).  All of this works and I see the new row in the datagridview, however; when I edit the values using the controls, the datagridview only reflects the first value I change.  If I then change rows in the datagridview or highlight the current row, the values update.  How can I get the datagridview to keep in sync with the underlying datasource?

A short example:
Imports System.ComponentModel

Public Class frmMisc
Private Class Test
        Public Sub New()
        End Sub

        Public Sub New(ByVal one As String,
                       ByVal two As String)
            Me.One = one
            Me.Two = two
        End Sub

        Public Property One
        Public Property Two
    End Class

    Private _data As BindingList(Of Test)

    Private Sub Misc_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        _data = New BindingList(Of Test)
        _data.Add(New Test("1", "2"))
        DataGridView1.DataSource = _data
    End Sub

    Private Sub DataGridView1_RowEnter(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowEnter
        Dim row As Test = DataGridView1.Rows(e.RowIndex).DataBoundItem
        If row IsNot Nothing Then
            TextBox1.DataBindings.Add("Text", row, "One")
            TextBox2.DataBindings.Add("Text", row, "Two")
        End If
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        _data.Add(New Test)
    End Sub
End Class

I didn't include the designer code for brevity.

Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 4 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros