none
Copy one datagridview to another datagridview in another form RRS feed

All replies

  • Hello,

    Please do not use formatting as you did in your post in the future.

    So to copy a DataGridView from one form to another form is to first ensure both forms are open and that the child form the DataGridView is scoped as Public.

    Add the following code module to your project. The language extension below will copy one row of the current DataGridView to the DataGridView on the other form which must have the same column order and data types else this will not work. Also this will not work if the target DataGridView has it's DataSource set which if this is the xase then you need to target the DataSource e.g. if you have used a DataTable then iterate the rows using someDataRow.ImportRow to copy the rows from DataGridView to DataGridView.

    Module DataGridViewExtensions
        ''' <summary>
        ''' Used to copy a row from one DataGridView to another DataGridView
        ''' </summary>
        ''' <param name="SingleRow"></param>
        ''' <param name="Target"></param>
        ''' <remarks>
        ''' Does not handle multiple rows selected
        ''' </remarks>
        <System.Diagnostics.DebuggerStepThrough()> _
        <System.Runtime.CompilerServices.Extension()> _
        Public Sub CloneRowWithValues(ByVal SingleRow As DataGridViewRow, ByVal Target As DataGridView)
    
            Dim Results As DataGridViewRow = CType(SingleRow.Clone(), DataGridViewRow)
    
    
            For Row As Int32 = 0 To SingleRow.Cells.Count - 1
                Results.Cells(Row).Value = SingleRow.Cells(Row).Value
            Next
    
            Target.Rows.Add(Results)
    
        End Sub
    
    End Module
    
    


    Please remember to mark the replies as answers if they help and unmarked 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.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Tuesday, April 16, 2019 3:30 PM
    Moderator
  • Hi

    So, you DO NOT want to copy one DGV to another DGV!

    What you seem to be asking is how to copy some/all columns on one DGV to another DGV. If that is the case, then you will need to give examples of the structure of each DGV, the means of populating one/both DGV before any copying, are either/both DGV bound to datasources, is destination DGV already populated with some data in columns other that those to be copied?

    Give examples of the data in first DGV and the datasource if any.

    Give example of any contents of second DGV and the datasource if any.


    Regards Les, Livingston, Scotland

    Tuesday, April 16, 2019 3:31 PM
  • Copy one datagridview to another datagridview in another form but they are not have the same number of column please help me

    Hi

    Without the needed information, this post is likely to be of no use to you.

    This example uses Form1 with a DataGridView1, Form2 with a DataGridView1.  Both DGV have some random data added to then via DataTables bound to them. The 2 Form DataGridViews have different number of rows (if form2 DGV has less that form1 DGV rowws then only form2 DGV rows will be filled otherwise only form1 DGV rows will be copied)

    To copy a column, right click in a column on the Form2 DGV and click Copy THIS column

    There is no exception handling included.

    If you try this example as a new stand alone test project and it fits with what you want, you could 'automate' the column copying by looping though the  form1 column indexes and calling the column copy sub.Form1 Code

    '  Form1 with BLANK DataGridView1
    Option Strict On
    Option Explicit On
    Public Class Form1
        Dim dt As New DataTable("Freddy")
        Dim r As New Random
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            With dt
                .Columns.Add("One", GetType(Integer))
                .Columns.Add("Two", GetType(String))
                .Columns.Add("Three", GetType(String))
                .Columns.Add("Four", GetType(Integer))
    
                For i As Integer = 1 To 10
                    .Rows.Add(i, r.Next(99, 199).ToString, (r.NextDouble * 199).ToString("0.00"), r.Next(999, 9999))
                Next
            End With
            DataGridView1.DataSource = dt
            Dim f2 As New Form2
            f2.Show()
        End Sub
    End Class

    Form2 Code

    '  Form2 with BLANK DataGridView1
    Option Strict On
    Option Explicit On
    Public Class Form2
        Dim cm As New ContextMenuStrip
        Dim col As Integer = 0
        Dim dt As New DataTable("Freddy")
        Dim r As New Random
        Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            With dt
                .Columns.Add("One", GetType(Integer))
                .Columns.Add("Two", GetType(String))
                .Columns.Add("Three", GetType(String))
                .Columns.Add("Four", GetType(Integer))
                .Columns.Add("Five", GetType(Integer))
                .Columns.Add("Six", GetType(String))
    
                For i As Integer = 1 To 12
                    .Rows.Add(Nothing, Nothing, Nothing, Nothing, r.Next(999, 9999), (r.NextDouble * 199).ToString("0.00"))
                Next
            End With
            With cm
                .Items.Add("Copy THIS Column")
            End With
            AddHandler cm.Click, AddressOf CopyTHISColumnToolStripMenuItem_Click
            With DataGridView1
                .DataSource = dt
                .ContextMenuStrip = cm
            End With
        End Sub
        Private Sub DataGridView1_CellContextMenuStripNeeded(sender As Object, e As DataGridViewCellContextMenuStripNeededEventArgs) Handles DataGridView1.CellContextMenuStripNeeded
            col = e.ColumnIndex
        End Sub
        Private Sub CopyTHISColumnToolStripMenuItem_Click(sender As Object, e As EventArgs)
            If col < Form1.DataGridView1.Columns.Count Then CopyColumn(col)
        End Sub
        Sub CopyColumn(source As Integer)
            For i As Integer = 0 To Form1.DataGridView1.Rows.Count - 1
                If Not i = Form1.DataGridView1.NewRowIndex AndAlso Not i >= DataGridView1.NewRowIndex Then
                    DataGridView1(source, i).Value = Form1.DataGridView1(source, i).Value
                End If
            Next
        End Sub
    End Class


    Regards Les, Livingston, Scotland

    Tuesday, April 16, 2019 5:02 PM
  • Okay, since my first reply was not fitting your requirements let's try doing this differently but requires the DataGridView to have a DataTable as it's DataSource.

    Doing this from a button

    Dim View As DataView = New DataTable(Ctype(someDataGridView.DataSource,DataTable)

    Dim dt As DataTable = view.ToTable("X","X","X")

    Where the X's are the columns to copy to the other DataGridView and in the other DataGridView it has columns defined were each column has it' DataPropertyName set to a column in the table dt above. Now iterate dt rows and do a ImportRow into the other DatagridView by casting it's DataSource to a DataTable


    Please remember to mark the replies as answers if they help and unmarked 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.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Tuesday, April 16, 2019 8:46 PM
    Moderator
  • thanks for help and my project like this:

    read from textfile to datagridview (have 4 columns that i will test if this imported data is correct or not from database (solved)after i will copy this to a new datagridview with different number of columns because i will insert a lot of new data in this new datagridview and update my database this is why i should have copy from datagridview to another with not the same numbers of columns but the first have 4 columns and those columns also exist in second form wich have more than 9 columns include the 4 columns

    this is how i want it work exactly

          Command      Article     Qte       PU

          abcd              abc15      20        1.2

          Command      Article     Qte       PU    Remise    Réf.Frs     Ensemble     Marge

          abcd              abc15      20        1.2     ........        .......          ..........         .......

    Wednesday, April 17, 2019 9:00 AM
  • thank you for help i just resolved my problem and i want a little help for other problem that i passed a lot of time to resolve it no solution

    i just want after getting data from text i want add new column from database i have tried a lot with no solution

      Command      Article     Qte       PU

      abcd              abc15      20        1.2

      Command      Article     Qte       PU         Designation

       abcd              abc15      20        1.2       from db

    Wednesday, April 17, 2019 9:38 AM
  • Hi,

    Is your problem solved? If so, please mark the useful replies as answers.  

    Best Regards,

    Alex


    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.

    Thursday, April 18, 2019 4:21 AM