简体   繁体   English

如何将 Databound Gridview 转换为 Datatable?

[英]How to cast Databound Gridview to Datatable?

I am trying to add row to my datagridview which is databound我正在尝试向数据绑定datagridview添加行

Code:代码:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    'Dim Index As Integer
    'Index = DataTable1DataGridView.CurrentCell.RowIndex
    Dim dt As DataTable = DataTable1DataGridView.DataSource
    Dim dr As DataRow = dt.NewRow
    dt.Rows.Add(dr)

End Sub

Error: Unable to cast object of type 'System.Windows.Forms.BindingSource' to type 'System.Data.DataTable'.错误:无法将类型为“System.Windows.Forms.BindingSource”的 object 转换为类型“System.Data.DataTable”。

here这里

Dim dt As DataTable = DataTable1DataGridView.DataSource

you have DataSource is object and it points to System.Windows.Forms.BindingSource , not DataTable .你有DataSource是 object 它指向System.Windows.Forms.BindingSource ,而不是DataTable

you need to get DataSource of the BindingSource您需要获取BindingSourceDataSource

dim ds as DataSet = 
    DirectCast(DirectCast(DataTable1DataGridView.DataSource, BindingSource).DataSource, DataSet)

You're doing it all wrong.你做错了。 You have a BindingSource for a reason so use it.你有一个BindingSource是有原因的,所以使用它。 You don't need to access the DataTable at all.您根本不需要访问DataTable Just use the BindingSource , which you should be able to refer to directly, so you don't need the grid either.只需使用BindingSource ,您应该可以直接引用它,因此您也不需要网格。

Dim rowView = DirectCast(DataTable1BindingSource.AddNew(), DataRowView)

rowView("SomeColumn") = someValue
DataTable1BindingSource.EndEdit()

When you bind a DataTable , the data actually comes from the DefaultView property, which is a DataView .绑定DataTable时,数据实际上来自DefaultView属性,即DataView That's why each item is a DataRowView rather than a DataRow .这就是为什么每个项目都是DataRowView而不是DataRow的原因。 You can treat a DataRowView just like you do a DataRow in many situations, including this one.在许多情况下,您可以像对待DataRow一样对待DataRowView ,包括这种情况。 If you have a typed DataSet though, you might prefer to use a typed DataRow .如果你有一个类型化的DataSet ,你可能更喜欢使用一个类型化的DataRow In that case, get the DataRow from the Row property of the DataRowView and cast it as the appropriate type:在这种情况下,从DataRowViewRow属性中获取DataRow并将其转换为适当的类型:

Dim rowView = DirectCast(DataTable1BindingSource.AddNew(), DataRowView)
Dim row = DirectCast(rowView.Row, DataTable1DataRow)

rowView.SomeColumn = someValue
DataTable1BindingSource.EndEdit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM