BlackCat
BlackCat

Reputation: 2044

How to cast Databound Gridview to Datatable?

I am trying to add row to my datagridview which is databound

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'.

Upvotes: 0

Views: 650

Answers (2)

jmcilhinney
jmcilhinney

Reputation: 54417

You're doing it all wrong. You have a BindingSource for a reason so use it. You don't need to access the DataTable at all. Just use the BindingSource, which you should be able to refer to directly, so you don't need the grid either.

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. That's why each item is a DataRowView rather than a DataRow. You can treat a DataRowView just like you do a DataRow in many situations, including this one. If you have a typed DataSet though, you might prefer to use a typed DataRow. In that case, get the DataRow from the Row property of the DataRowView and cast it as the appropriate type:

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

rowView.SomeColumn = someValue
DataTable1BindingSource.EndEdit()

Upvotes: 1

T.S.
T.S.

Reputation: 19330

here

Dim dt As DataTable = DataTable1DataGridView.DataSource

you have DataSource is object and it points to System.Windows.Forms.BindingSource, not DataTable.

you need to get DataSource of the BindingSource

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

Upvotes: 2

Related Questions