Reputation: 203
Referring to this question: StackOverflowException was unhandled in VB.NET I decided to create a new question because I have a new error.
Unable to cast object of type 'System.Windows.Forms.BindingSource' to type 'System.Data.DataTable'.
CODE (in button click event):
' 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()
The error, which is in the image, is in dt As DataTable = CType(frmEncodeDatabase.EncodingDataGridView.DataSource, DataTable).Copy
where the error is right now. How will I modify the code?
Upvotes: 0
Views: 954
Reputation: 9981
The error message is self-explainable.
"Unabled to cast object of type 'BindingSource' to type 'DataTable'."
The datassource of your datagridview is a BindingSource, so you need to cast to this type.
Dim bs As BindingSource = CType(frmEncodeDatabase.EncodingDataGridView.DataSource, BindingSource)
Assuming that the datasource of the bindingsource is a datatable:
Dim dt As DataTable = CType(bs.DataSource, DataTable)
If not, you'll get another cast exception, but now you how to fix it.
Upvotes: 1