none
Copy selected rows from one datagrid view to another VB.NET RRS feed

  • Question

  • i have 2 datagridviews in 2 forms.Now dgvw 1  has a Checkbox column...What i want is , when a user checks a rows checkbox(or many selects multiple rows), the rows will immediately be added to the 2nd dgvw in form 2...I found this code :

    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 

    The problem with this code is, when a user selects a row from dgvw 1 , it appears in dgvw2 but it disappears from dgvw1 which i don't want......Now,

    1 . Either help me to copy the selected rows to another datagridview without a button press(i mean it will copy as soon as a user checks a rows checkbox)

    2. Or suppose a user has selected multiple rows....then on a button click all the selected rows will be shown at the top of the dgvw(i mean when a user makes scattered selections,all the selections will line up at the top)

    NOTE : The first column of dgvw 1 is frozen!!


    Tuesday, October 31, 2017 4:39 AM

All replies

  • The problem with this code is, when a user selects a row from dgvw 1 , it appears in dgvw2 but it disappears from dgvw1 which i don't want

    If you don't want the first DGV to be updated as a result of the selection, then you should comment out the lines of code that do the updating:

    ' create Source DV as Selected = False
    dvSource = New DataView(dtSample, "Selected=False", "", DataViewRowState.CurrentRows)
    dgv1.DataSource = dvSource

    Tuesday, October 31, 2017 5:39 AM
  • hello, i am using this code now :

        Private Sub userdatagrid_SelectionChanged(sender As Object, e As EventArgs) Handles userdatagrid.SelectionChanged
            Dim c, t As Integer
            Selected.dg2.Columns.Clear()
            For t = 0 To userdatagrid.Columns.Count - 1
                Selected.dg2.Columns.Add(userdatagrid.Columns(t).Clone())
            Next
            For c = 0 To userdatagrid.Rows.Count - 1
                If userdatagrid.Rows(c).Cells(0).Value = True Then
                    Selected.dg2.Rows.Add(userdatagrid.Rows(c).Cells(0).Value, userdatagrid.Rows(c).Cells(1).Value, userdatagrid.Rows(c).Cells(2).Value, userdatagrid.Rows(c).Cells(3).Value, userdatagrid.Rows(c).Cells(4).Value, userdatagrid.Rows(c).Cells(5).Value, userdatagrid.Rows(c).Cells(6).Value, userdatagrid.Rows(c).Cells(7).Value, userdatagrid.Rows(c).Cells(8).Value, userdatagrid.Rows(c).Cells(9).Value, userdatagrid.Rows(c).Cells(10).Value, userdatagrid.Rows(c).Cells(11).Value, userdatagrid.Rows(c).Cells(12).Value, userdatagrid.Rows(c).Cells(13).Value, userdatagrid.Rows(c).Cells(14).Value, userdatagrid.Rows(c).Cells(15).Value, userdatagrid.Rows(c).Cells(16).Value, userdatagrid.Rows(c).Cells(17).Value, userdatagrid.Rows(c).Cells(18).Value, userdatagrid.Rows(c).Cells(19).Value, userdatagrid.Rows(c).Cells(20).Value, userdatagrid.Rows(c).Cells(21).Value, userdatagrid.Rows(c).Cells(22).Value, userdatagrid.Rows(c).Cells(23).Value, userdatagrid.Rows(c).Cells(24).Value, userdatagrid.Rows(c).Cells(25).Value, userdatagrid.Rows(c).Cells(26).Value, userdatagrid.Rows(c).Cells(27).Value, userdatagrid.Rows(c).Cells(28).Value, userdatagrid.Rows(c).Cells(29).Value, userdatagrid.Rows(c).Cells(30).Value)
                End If
            Next
        End Sub

       Private Sub form2_load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim img As DataGridViewImageColumn
            img = dg2.Columns(1)
            img.ImageLayout = DataGridViewImageCellLayout.Stretch
        End Sub

       Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
            Selected.Show()
        End Sub

    The problem with this code is, if i check only one row/checkbox and click on button 6, the dgvw on form 2 appears to br rmpty. I need to select/check two rows and then only one of the rows appear. The second problem is, suppose a user checks only one checkbox, and clicks on the button , the dgv on form 2 is empty(i said that already) but if the user closes form 2 and reopens it with button6, it gives an INDEX OUT OF RANGE exception in form 2's  IMG=DG2.COLUMNS(1) ....how to fix these problems ??

    Tuesday, October 31, 2017 2:27 PM
  • Try separating the two views by fist using Dim Clone As DataTable = dtSample.Copy which means anything you do to the clone does not reflect back to the original DataTable which I think is happening currently if rows are disappearing.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, October 31, 2017 7:44 PM
    Moderator
  • Okay, here is something, had to wait as I could not do this at work. This works via a button, does the data view as I explained earlier today via cloning, used ImportRow to copy the row to the other DataTable on the Child form. The child form BTW will follow the main form when moving the main form. Nothing is lost on the main form when doing the data view.

    https://1drv.ms/u/s!AtGAgKKpqdWjiG7qHoJNU0F4xQex

    You need to run the script in the solution to create the database, a table and populate the table.

    BackEnd project does only data access while FrontEnd does just that, user interface work. This was a 30 minute project from start to finish.

    If you want the second DataGridView on the same form then it's easy enough to change to fit that.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Wednesday, November 1, 2017 12:12 AM
    Moderator
  • Hi Aousaf,

    >>1 . Either help me to copy the selected rows to another datagridview without a button press(i mean it will copy as soon as a user checks a rows checkbox)

    When you check datagridview row, this row value will be added into list(of datagridviewrow), then pass this list to another form.

    Public targetRows = New List(Of DataGridViewRow)
        Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView1.SelectionChanged
            targetRows.clear()
            For Each row As DataGridViewRow In DataGridView1.Rows
                If row.Cells(0).Value = 1 Then
                    Dim targetRow = CType(row.Clone(), DataGridViewRow)
                    For Each cell As DataGridViewCell In row.Cells
                        targetRow.Cells(cell.ColumnIndex).Value = cell.Value
                    Next
                    targetRows.Add(targetRow)
                End If
            Next
        End Sub

    >>2. Or suppose a user has selected multiple rows....then on a button click all the selected rows will be shown at the top of the dgvw(i mean when a user makes scattered selections,all the selections will line up at the top)

    If you want to sort by checkbox state, you can use BindSource to sort.

     Dim dt As New DataTable
        Dim source1 As New BindingSource()
    
        Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim str As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\C# and VB Support\Example(VB)\Sample\Data1.mdf;Integrated Security=True"
            Dim sql As String = "Select 0 as IsSelect, * from Test9"
            Dim conn As New SqlConnection(str)
            Using cmd As New SqlCommand(sql, conn)
                conn.Open()
                Using adapter As New SqlDataAdapter(cmd)
                    adapter.Fill(dt)
    
                End Using
                conn.Close()
            End Using
            Dim view1 As New DataView(dt)
            source1.DataSource = view1
            DataGridView1.DataSource = view1
            DataGridView1.Refresh()
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            source1.Sort = "IsSelect DESC"
        End Sub
    

    Best Regadrs,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, November 1, 2017 3:28 AM
    Moderator
  • Hi Aousaf,

    >>1 . Either help me to copy the selected rows to another datagridview without a button press(i mean it will copy as soon as a user checks a rows checkbox)

    When you check datagridview row, this row value will be added into list(of datagridviewrow), then pass this list to another form.

    Public targetRows = New List(Of DataGridViewRow)
        Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView1.SelectionChanged
            targetRows.clear()
            For Each row As DataGridViewRow In DataGridView1.Rows
                If row.Cells(0).Value = 1 Then
                    Dim targetRow = CType(row.Clone(), DataGridViewRow)
                    For Each cell As DataGridViewCell In row.Cells
                        targetRow.Cells(cell.ColumnIndex).Value = cell.Value
                    Next
                    targetRows.Add(targetRow)
                End If
            Next
        End Sub

    >>2. Or suppose a user has selected multiple rows....then on a button click all the selected rows will be shown at the top of the dgvw(i mean when a user makes scattered selections,all the selections will line up at the top)

    If you want to sort by checkbox state, you can use BindSource to sort.

     Dim dt As New DataTable
        Dim source1 As New BindingSource()
    
        Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim str As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\C# and VB Support\Example(VB)\Sample\Data1.mdf;Integrated Security=True"
            Dim sql As String = "Select 0 as IsSelect, * from Test9"
            Dim conn As New SqlConnection(str)
            Using cmd As New SqlCommand(sql, conn)
                conn.Open()
                Using adapter As New SqlDataAdapter(cmd)
                    adapter.Fill(dt)
    
                End Using
                conn.Close()
            End Using
            Dim view1 As New DataView(dt)
            source1.DataSource = view1
            DataGridView1.DataSource = view1
            DataGridView1.Refresh()
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            source1.Sort = "IsSelect DESC"
        End Sub

    Best Regadrs,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    i figured it out...Now,have another issue. Please re-read my code.What i want now is , suppose a user checks a checkbox of a row, it gets added to the 2nd dgvw. What i want is , when a user unchecks a row after checking it first, the row will also disappear from dgvw 2 as well...any way to do dat ?
    Wednesday, November 1, 2017 4:01 AM
  • Okay, here is something, had to wait as I could not do this at work. This works via a button, does the data view as I explained earlier today via cloning, used ImportRow to copy the row to the other DataTable on the Child form. The child form BTW will follow the main form when moving the main form. Nothing is lost on the main form when doing the data view.

    https://1drv.ms/u/s!AtGAgKKpqdWjiG7qHoJNU0F4xQex

    You need to run the script in the solution to create the database, a table and populate the table.

    BackEnd project does only data access while FrontEnd does just that, user interface work. This was a 30 minute project from start to finish.

    If you want the second DataGridView on the same form then it's easy enough to change to fit that.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    i figured it out...Now,have another issue. Please re-read my code.What i want now is , suppose a user checks a checkbox of a row, it gets added to the 2nd dgvw. What i want is , when a user unchecks a row after checking it first, the row will also disappear from dgvw 2 as well...any way to do dat ?
    Wednesday, November 1, 2017 4:01 AM
  • Here is my suggestion.

    https://1drv.ms/u/s!AtGAgKKpqdWjiG-Irpmxi1EXsMeG

    Main code, there is more in the zip file. The main concept here is to hold the primary key and checked state in a list of a concrete class.

    Imports BackEnd
    Public Class Form1
        Private mChildForm As ChildForm
        Private mFirstTime As Boolean = True
        WithEvents bsData As New BindingSource
        Public Property DataGridViewItemList As List(Of DataGridViewItem)
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim Operations As New Operations
            bsData.DataSource = Operations.Read
            DataGridView1.DataSource = bsData
            DataGridViewItemList = Operations.DataGridViewItemList
    
            DataGridView1.Columns("Process").HeaderText = ""
            DataGridView1.Columns("Process").Width = 35
            DataGridView1.Columns("FirstName").HeaderText = "First"
            DataGridView1.Columns("LastName").HeaderText = "Last"
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            Dim dt As DataTable = CType(bsData.DataSource, DataTable)
            Dim childDataTable = dt.Clone
    
            If Not My.Application.IsFormOpen("ChildForm") Then
                mChildForm = New ChildForm
                mChildForm.DataGridView1.DataSource = childDataTable
                mChildForm.Owner = Me
                mFirstTime = True
            End If
    
            mChildForm.Show()
    
            If mFirstTime Then
                mChildForm.Location = New Point(Me.Left + Me.Width, Top)
                mFirstTime = False
            End If
    
            Dim dtClone As DataTable = dt.Copy
    
            dtClone.DefaultView.RowFilter = "Process=true"
    
            For Each rowView As DataRowView In dtClone.DefaultView
                Dim row As DataRow = rowView.Row
                Dim result = childDataTable.AsEnumerable.FirstOrDefault(Function(r) r.Field(Of Integer)("id") = row.Field(Of Integer)("Id"))
                If result Is Nothing Then
                    childDataTable.ImportRow(row)
                End If
    
            Next
    
            mChildForm.DataGridView1.DataSource = childDataTable
    
        End Sub
        Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
            Dim dt As DataTable = CType(bsData.DataSource, DataTable)
            dt.Columns("Process").ColumnMapping = MappingType.Hidden
            mChildForm = New ChildForm
            mChildForm.Owner = Me
            mChildForm.DataGridView1.DataSource = dt.Clone
            mChildForm.Show()
    
            mChildForm.Location = New Point(Me.Left + Me.Width, Top)
            mFirstTime = False
    
            My.Application.OpenForms(0).Activate()
    
            AddHandler DataGridView1.CellValueChanged, AddressOf DataGridView1_CellValueChanged
        End Sub
        Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
            If mChildForm IsNot Nothing Then
                mChildForm.Dispose()
            Else
                '  mChildForm is Nothing
            End If
        End Sub
        Private Sub Form1_LocationChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LocationChanged
            If Not mFirstTime Then
                mChildForm.Location = New Point(Left + Width, Top)
            End If
        End Sub
        Private Sub DataGridView1SelectAll_CurrentCellDirtyStateChanged(ByVal sender As Object, ByVal e As EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged
    
            If TypeOf DataGridView1.CurrentCell Is DataGridViewCheckBoxCell Then
                DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
            End If
    
        End Sub
        Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
    
            If DataGridView1.CurrentRow.IsNewRow Then
                Exit Sub
            End If
    
            If DataGridView1.CurrentRow IsNot Nothing Then
    
                Dim SelectedColumnName = DataGridView1.Columns(DataGridView1.CurrentCellValue.ColumnIndex).Name
                If SelectedColumnName = "Process" Then
    
                    If CType(bsData.Current, DataRowView).Row.IsNull("id") Then
                        Exit Sub
                    End If
    
                    Dim result = DataGridViewItemList.FirstOrDefault(Function(row) row.Id = CType(bsData.Current, DataRowView).Row.Field(Of Integer)("id"))
    
                    If DataGridView1.CurrentRowProcessed Then
                        result.Checked = True
                    Else
                        RemoveHandler DataGridView1.CellValueChanged, AddressOf DataGridView1_CellValueChanged
                        bsData.RemoveCurrent()
                        AddHandler DataGridView1.CellValueChanged, AddressOf DataGridView1_CellValueChanged
                    End If
                End If
            End If
        End Sub
        Private Sub DataGridView1_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles DataGridView1.DataError
            e.Cancel = True
            SendKeys.Send("{ESC}")
        End Sub
    End Class
    Now there is a caveat to this, removal of rows using a DataView means that they will also be removed from the other DataGridView. This can be changed too but I need to head off to work and will not be able to work on it until either tonight or tomorrow morning at this time. So I suggest if this works for you (current code) then work with it.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Wednesday, November 1, 2017 10:10 AM
    Moderator
  • Was this answer what you are using now e.g. someone provided a solution

    https://stackoverflow.com/questions/37113690/show-checked-rows-into-another-datagridview


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Wednesday, November 1, 2017 10:30 PM
    Moderator