【问题标题】:InvalidCastException was unhandled in VB.NETVB.NET 中未处理 InvalidCastException
【发布时间】:2014-12-25 05:13:02
【问题描述】:

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

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

代码(在按钮点击事件中):

' 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 中,错误现在就在其中。我将如何修改代码?

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    错误消息是不言自明的。

    无法将 'BindingSource' 类型的对象转换为 'DataTable' 类型。

    你的datagridview的数据源是BindingSource,所以你需要转换成这个类型。

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

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

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

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

    【讨论】:

    • 我在 dt As DataTable = CType(bs.DataSource, DataTable) 中有另一个强制转换异常 它说:“INVALIDCASTEXCEPTION:无法强制转换类型为“Golden_Dragon_Billing_System.EncodingCompleteDataSet”的对象输入“System.Data.DataTable”。错误图片:postimg.org/image/a9c5tsb93
    • 您需要查看我的源项目吗?我厌倦了这个!
    • @CodingSource 不,我不需要查看您的源项目,但需要再次阅读我的答案。我假设您的 bindingsource 的数据源是一个数据表,但事实并非如此。那么人们可能会想知道什么呢?如果您仔细阅读 new 错误消息,您会发现它是 DataSet。所以你需要把它转换成EncodingCompleteDataSet。请原谅我,但我的水晶球在预测下周的乐透号码时坏了。
    • @CodingSource 这解决了您的问题,因此请单击绿色复选标记将其标记为“已接受”。这样人们就知道问题已经解决了。而且,作为奖励,你获得 +2 声望和徽章。
    猜你喜欢
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 2012-11-24
    相关资源
    最近更新 更多