Click here to Skip to main content
15,885,669 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear fellow programmers,

My goal is to move rows from a datagridview that has no datasource to another datagridview in another form that is data-bounded. When I click the button the rows move/save to that data-bounded datagridview.

So here is my following code:
' Copy rows from the first datagridview to the second datagridview that is data bound
    ' First copy the second datagridviews datasource into a new data table

    Dim dt As DataTable = CType(frmEncodeDatabase.EncodingDataGridView.DataSource, DataTable).Copy
    Dim dr As DataRow

    ' Loop through all rows of the first datagridview and copy them into the data table

    For r As Int32 = 0 To Me.DataGridViewX1.Rows.Count - 1
        If Me.DataGridViewX1.Rows(r).IsNewRow = False Then   ' Do not copy the new row
            dr = dt.NewRow

            ' Loop through all cells of the first datagridview and populate the data row

            For c As Int32 = 0 To Me.DataGridViewX1.ColumnCount - 1
                dr(c) = Me.DataGridViewX1.Rows(r).Cells(c).Value
            Next

            dt.Rows.Add(dr) ' Add the data row to the data table
        End If
    Next

    Me.DataGridView2.DataSource = dt    ' Rebind the second datagridview with the new table which has all the rows from both datagridviews
    frmEncodeDatabase.show()


So there comes the error at
dt As DataTable = CType(frmEncodeDatabase.EncodingDataGridView.DataSource, DataTable).Copy
. It says InvalidCastException was unhandled.

To get a better view on the error, please look at the link (image): http://postimg.org/image/k65b52bxn/[^]


Any help/suggestion/code will be appreciated,
Genesis
Posted

1 solution

Well, start by using teh debugger to find out exactly what frmEncodeDatabase.EncodingDataGridView.DataSource actually is.
Until you know that, you are just guessing...

So put a breakpoint on the line, run your app and when it hits it, look at the values.

But without the code that sets the value (where ever that is) we can't help you any further.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900