在VB.NET中未处理InvalidCastException

时间:2014-12-25 05:13:03

标签: vb.net

参考这个问题:StackOverflowException was unhandled in VB.NET我决定创建一个新问题,因为我有一个新错误。

  

无法将“System.Windows.Forms.BindingSource”类型的对象强制转换为“System.Data.DataTable”。

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()

图片中的错误位于dt As DataTable = CType(frmEncodeDatabase.EncodingDataGridView.DataSource, DataTable).Copy,现在错误正确。我该如何修改代码?

1 个答案:

答案 0 :(得分:1)

错误消息是可自我解释的。

  

无法将'BindingSource'类型的对象投射到'DataTable'。

您的datagridview的数据源是BindingSource,因此您需要转换为此类型。

Dim bs As BindingSource = CType(frmEncodeDatabase.EncodingDataGridView.DataSource, BindingSource)

假设bindingsource的数据源是数据表:

Dim dt As DataTable = CType(bs.DataSource, DataTable)

如果没有,你会得到另一个强制转换异常,但现在你要解决它。