Show checked rows into another DataGridView

Copying rows to a new DataTable is wasteful because the only real difference between the two is whether some Boolean value is True or False. Since you are binding to a DataTable, you can simply change the view displayed in each DGV.

The concept expressed in the title, show checked rows… is different than copying rows to another control as the code tries to do. This will show how to use one DataSource to display some rows in each DGV.

If your data comes from a database, you can add a column in the SQL:

' Access version
Dim sql = "SELECT a, b, c, False AS Selected FROM SAMPLE"

This will add a Boolean Column initialized to False for all rows and will display in the DGV as a CheckBox.

If the data gets into the DataTable some other way, add the column manually:

dtSample.Columns.Add("Selected", GetType(Boolean))
dtSample.Columns("Selected").DefaultValue = False

' we need to loop and set a value
' if you manually add a column
For Each r As DataRow In dtSample.Rows
    r("Selected") = False
Next

To display rows in one grid (or listbox or combo) or the other based on that value, this code will use 2 DataViews. If you are using views, you often want to change the RowFilter as you go, so make a few things global to the form:

Private dtSample As DataTable          ' base table for BOTH DGVs
Private dvSource As DataView           ' ALL or Selected = False view
Private dvDest As DataView             ' Selected only
...
' build datatable and add the Selected Row (if needed)
...
' create Source DV as Selected = False
dvSource = New DataView(dtSample, "Selected=False", "", DataViewRowState.CurrentRows)

' create SELECTED DV as Selected = True
dvSelected = New DataView(dtSample, "Selected=True", "",DataViewRowState.CurrentRows)

dgv1.DataSource = dvSource
dgv2.DataSource = dvSelected 

dvSource is optional. If you want all rows to show in the first DGV, you that DataView (this appears to be the case as per the question).

For illustrative purposes, this is set up so that as items are checked in DGV1 they “disappear” from it (because they no longer meet the Selected = False criteria), and automagically appear in DGV2 (because, now they do meet that criteria. Results:

enter image description here

Rows unchecked/unselected in the bottom DGV will skitter back to the top one.

It is economical. Not only do you not have to run any code at all to appear to add or move a row to the second DGV, but you are not making copies of DataRows and a new DataTable to do so. Going by TaskManager (rough, but indicative), the amount of memory stays about the same as Selected Rows change; when manually copying them, it slowly creeps up as you make copies of DataRows containing the same identical data.

Leave a Comment