3
votes

I am populating a DataGridView (grid1) either by DataTable or DataSet.
I can remove a set of selected rows then add them to another unbound DataGridView (grid2).
The problem arises when I take a row from grid2 then add it to grid1.

Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.

This occurs because

grid1.DataSource = myDataTable
or
grid1.DataSource = myDataSet

but when I do

grid1.DataSource = Nothing

all the rows from grid1 is removed.

Is there anyway to detach a datagridview from its datasource but keep the rows?

3

3 Answers

0
votes

I can think of a solution wherein I would add another unbound DataGridView (grid3),
copy the content of the bound datagridview (grid1) to grid3 programmatically
then manipulate it from there.

0
votes

I haven't tried this, but have a look at the Copy method:

grid1.DataSource = myDataTable.Copy

The MSDN says "Copies both the structure and data for this DataTable." It may be that copying it also un-binds it.

0
votes

If you have a databound grid, you should probably not be playing with the rows in the grid at all. Alter the table that you set as the datasource, then the grid will reflect the new rows.

dim row as datarow = myDataTable.newrow()
row.item("Column1") = "new value"
myDataTable.rows.add(row)

now the new row will show up on the databound grid. You can remove rows from the grid by removing it from the datasource datatable as well.