Help with updating DataGridView2 based on changes in DataGridView1


When I delete a row in DataGridView1, how do I automatically a row inDataGridView2 with the same ID? Also When I add a new row in DataGridView1 how do I automatically increment the ID column and also add a new row with same ID in DataGridView2 using VB.NET?


Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Éric MoreauSenior .Net ConsultantCommented:
You better use a BindingSource:

    private bs as new BindingSource

    Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
        dim ds as New DataSet
        ds.ReadXml("data.xml", XmlReadMode.ReadSchema)

        bs.DataSource = ds.Tables(0)
        DataGridView1.DataSource = bs 
        DataGridView2.DataSource = bs
    End Sub

Open in new window

vcharlesAuthor Commented:

Thanks for the code, can it be fom from Grid? The Grids are bound to different  tables.

Éric MoreauSenior .Net ConsultantCommented:
what about:
Private Sub btnGenerate_Click(sender As Object, e As EventArgs) Handles btnGenerate.Click
        'Create a table
        Dim dt As New DataTable("Person")
        With dt
            .Columns.Add("ID", GetType(Int32))
            .Columns.Add("FirstName", GetType(String))
            .Columns.Add("LastName", GetType(String))

            'Add rows
            .LoadDataRow(New Object() {1, "Joe", "Dalton"}, True)
            .LoadDataRow(New Object() {2, "Jack", "Dalton"}, True)
            .LoadDataRow(New Object() {3, "Willam", "Dalton"}, True)
            .LoadDataRow(New Object() {4, "Averel", "Dalton"}, True)
        End With

        DataGridView1.DataSource = dt
        DataGridView2.DataSource = dt.Copy
    End Sub

    Private Sub DataGridView1_DefaultValuesNeeded(sender As Object, e As DataGridViewRowEventArgs) Handles DataGridView1.DefaultValuesNeeded
        'get the reference to the datatable
        dim dt as DataTable = DirectCast(DataGridView1.DataSource, DataTable)

        'Find the current max value
        dim id as Integer = DirectCast(dt.Compute("MAX(ID)", ""), Integer)

        'set the new ID
        e.Row.Cells("ID").value = id + 1

        'Add row to the second grid
        dim dt2 as DataTable = DirectCast(DataGridView2.DataSource, DataTable)
        dim r As DataRow = dt2.NewRow()
        r("ID") = id+1
    End Sub

    Private Sub DataGridView1_UserDeletingRow(sender As Object, e As DataGridViewRowCancelEventArgs) Handles DataGridView1.UserDeletingRow
        'find the ID of the deleted row
        dim id as String = e.Row.Cells("ID").Value.ToString()

        'get the reference to the datatable
        dim dt as DataTable = DirectCast(DataGridView2.DataSource, DataTable)
        'find the related rows
        dim dr As DataRow() = dt.Select("ID = " + id)
        'delete it
        if dr.Length>=1 Then
        End If
    End Sub

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

vcharlesAuthor Commented:

When I click on a cell in a new row, I receive the following error:

Unable to cast object of type 'System.Windows.Forms.BindingSource' to type 'System.Data.DataTable'.

On line:
        Dim dt As DataTable = DirectCast(DataGridView1.DataSource, DataTable)

How do I fix this error?


vcharlesAuthor Commented:
I am using the code below to load the Grid.

  Dim bs As New BindingSource()
     fslinkBEL = New System.IO.FileStream(Application.StartupPath + "\aop40.xml", IO.FileMode.Open)

        bs.DataSource = dtsetlinkBEL.Tables(0)
        DataGridView1.DataSource = bs
Éric MoreauSenior .Net ConsultantCommented:
you are surely not using the code of my latest post. there isn't any BindingSource in there!
Éric MoreauSenior .Net ConsultantCommented:
change the last 2 lines for:
 DataGridView1.DataSource =dtsetlinkBEL.Tables(0)

Open in new window

vcharlesAuthor Commented:

I made the change but received the following error:

"specified  cast not valid"

on line:

Dim id As Integer = DirectCast(dt.Compute("MAX(ID)", ""), Integer)

How do I solve this error?


Éric MoreauSenior .Net ConsultantCommented:
Have you tried my code has is? It should be working as it was working on my computer!

Now If you took bits here and there pasting in your code and you only show me one line, I can't easily figure it out. Do you have an ID column in your grid? Does that column contains valid INTEGER values on each rows?
vcharlesAuthor Commented:

It's working.

Thank you.

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.