locked
Copy Row From One DataGridView To Another RRS feed

  • Question

  • Hi,

    Could someone please help me, i am trying to use this code to copy data(a Row) from one DataGridView to another on a double click. thing is I need to have DataTable1 bound to BindingSource1 bound to DataGridView1, and also BindingSource2 bound to DataGridView2.

    How do i bind DataTable1 to BindingSource1 to DataGridView1?

    This is what i did so far.....

     

     

    Dim DataTable2 As DataTable = DataTable1.Clone()

    For Each row As DataGridViewRow In DataGridView1.SelectedRows
    DataTable2.ImportRow(DirectCast(row.DataBoundItem, DataRowView).Row)
    Next row

    BindingSource2.DataSource = DataTable2

    Friday, August 15, 2008 10:32 AM

Answers

  • Hi Princy_Jones,

     

    My above code snippet isn't good enough to be used in your scenario.It is the best option to modify it based on your scenario. First you need to know if you don't select the whole data row, just some independent cells, how you modify the second datagridview control. I don't know your application logic. I think that you can use the DataGridView1.SelectedCells to know all selected cells in the one datagridview. In this scenario you use databinding to bind the datatable to the datagridview. Actually you can modify the underlying datatable object for the other datagridview for this issue. Read the following links for your reference:

     

    1. Manipulating Data in a DataTable. How to add, view, edit, and delete data in the table; how to monitor errors and events and query the data in the table.

     

    2. DataGridView Control (Windows Forms). The topics in this section describe the concepts and techniques that you can use to build DataGridView features into your applications.

     

    Best regards,

    Riquel

    Thursday, August 21, 2008 5:51 AM
    Moderator

All replies

  • Hi Princy_Jones,

     

    Based on your post, you need to add copy and paste functionality for datagridview. We can use clipboard with custom data format to implement this. For more information about custom data format, visit http://www.codeproject.com/KB/shell/clipboard02.aspx. Here is the code example about this method. Modify it for your use. Put two datagridviews in the form to run.Try the following code snippet. It should satisfy your requirement.

     

    Imports System.Windows.Forms

    Public Class Form1

        Private dt As New DataTable()

        Private dt1 As New DataTable

        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

            My.Computer.Clipboard.Clear()

            Me.KeyPreview = True

            dt.Columns.Add("num1", GetType(Integer))

            dt.Columns.Add("num2", GetType(Double))

            dt.Columns.Add("str1", GetType(String))

            For i As Integer = 0 To 10

                dt.Rows.Add(i, i * 0.56, "str " & i.ToString)

            Next

            dt.AcceptChanges()

            DataGridView1.DataSource = dt

            Me.DataGridView1.AutoSize = True

            Me.KeyPreview = True

            dt1 = dt.Clone

            DataGridView2.DataSource = dt1

        End Sub

        Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown

            If (e.KeyCode = Keys.C And e.Control And DataGridView1.SelectedRows.Count > 0) Then

                DataGridView1.EndEdit()

                If (DataGridView1.Focused) Then

                    e.SuppressKeyPress = True

                    Dim ido As IDataObject = New DataObject

                    Dim cd As New CustomData()

                    cd.rowlist = dt.Clone

                    For i As Integer = 0 To DataGridView1.SelectedRows.Count - 1

                        cd.rowlist.Rows.Add(dt.Rows(DataGridView1.SelectedRows(i).Index).ItemArray)

                    Next

                    ido.SetData(CustomData.Format.Name, False, cd)

                    My.Computer.Clipboard.SetDataObject(ido)

                End If

            ElseIf (e.KeyCode = Keys.V And e.Control) Then

                DataGridView1.EndEdit()

                If (DataGridView2.Focused) Then

                    e.SuppressKeyPress = True

                    Dim ido As IDataObject = Clipboard.GetDataObject()

                    If (ido.GetDataPresent(CustomData.Format.Name)) Then

                        Dim cd As CustomData = CType(ido.GetData(CustomData.Format.Name), CustomData)

                        For i As Integer = 0 To cd.rowlist.Rows.Count - 1

                            dt1.Rows.Add(cd.rowlist.Rows(i).ItemArray)

                        Next

                    End If

                End If

            End If

        End Sub

    End Class

    <Serializable()> _

    Public Class CustomData

        Private Shared _format As DataFormats.Format

        Private _rowlist As DataTable

        Shared Sub New()

            ' Registers a new data format with the windows Clipboard

            _format = DataFormats.GetFormat(GetType(CustomData).FullName)

        End Sub

        Public Sub New()

            MyBase.New()

        End Sub

        Public Shared ReadOnly Property Format() As DataFormats.Format

            Get

                Return _format

            End Get

        End Property

        Public Property rowlist() As DataTable

            Get

                Return _rowlist

            End Get

            Set(ByVal value As DataTable)

                _rowlist = value

            End Set

        End Property

        Public Overrides Function ToString() As String

            Return "customized format"

        End Function

    End Class

     

    Best regards,

    Riquel

     

    Tuesday, August 19, 2008 9:50 AM
    Moderator
  • Hi Riquel Dong – MSFT,

     

    Thanks alot for your response to my question, it is much appreciated,   i have tried what you have told me, but i'm jus getting data in DataGridView2, with the columns added. I'm not sure if you know, but i am binding a Access Database table to DataGridView1 I tried something else also but with this code when i double click a row in DataGridView1 it adds the row from DataGridView1 to DataGridView2, but each time i click a row, a whole new set of columns is being added. Heres the code....

     

    Code Snippet

    Private Sub dg1_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dg1.MouseDoubleClick

     

    Dim val1 As String

    Dim val2 As String

    Dim val3 As String

    Dim val4 As String

    Dim val5 As String

    Dim notick As String

    Dim check As Boolean

    check = False

    For Each row As DataGridViewRow In dg1.SelectedRows

    val1 = row.Cells(0).Value

    val2 = row.Cells(1).Value

    val3 = row.Cells(2).Value

    val4 = row.Cells(3).Value

    While check = False

    notick = InputBox("Please enter the quantity")

    If notick = "" Then

    Exit Sub

    End If

    If IsNumeric(notick) Then

    '''TB2.Text = notick

    If val3 >= notick Then

    check = True

    Else

    MsgBox("Please submit a value less than Quantity on Hand", MsgBoxStyle.Information)

    End If

    Else

    MsgBox("Please sumbit an integer value", MsgBoxStyle.Information)

    ' Call Saila()

    End If

    End While

    'TB2.Text = row1.Cells.Count

    'TB2.Text = row1.SetValues("1")

    'TB2.Text = row1.Cells.Insert(")

    dg2.Columns.Add("Col1", "PartNo")

    dg2.Columns.Add("Col2", "Description")

    dg2.Columns.Add("Col3", "Latest Selling Price")

    dg2.Columns.Add("Col4", "Quantity")

    ' dg2.UpdateCellValue(0, 0)

    dg2.Rows.Insert(0, val1, val2, val4, notick)

    'DG2.Rows.Insert(2, val3)

    'DG2.Rows.Insert(3, val4)

    Next

    End Sub

     

     

     

    If you can please help me it will be much appreciated.....

    Heres some code i searched for but i cant get it to work....

     

    How can I copy all of the selected cells of my first DataGridView so that it will show on my second one?

    On my first DataGridView(dgvMain), columns are clmDate and clmName and it was populated through my dataset, now setting the grid to FullRowSelect in SelectionMode property I want that whatever I had selected will be reflected in the second grid(dgvDetails)
    Assuming that both DataGridViews had similar column collection.

    Here's what I had so far:
    For Each row As DataGridViewCell In Me.dgvMain.SelectedCells
    Me.dgvDetails.Rows.Add(row.Value.ToString)
    Next
    What the code actually executed is that it loads all of the selected cells into the first coulmn of dgvDetails only leaving the second column empty.

     

    talkro

    Mar 26th, 2007, 04:23 AM

    for Each row As DataRow In Me.dgvMain.SelectedRows
    me.dgvDetails.Rows.Add(row)
    Next

     

    aldrean

    Mar 26th, 2007, 07:12 PM

    Thanks talkro for you response, but unfortunately, your code gives me this exception:Unable to cast object of type 'System.Windows.Forms.DataGridViewRow' to type 'System.Data.DataRow'.

    Hope somebody can help..Thanks...

     

    jmcilhinney

    Mar 26th, 2007, 08:27 PM

    I would suggest not copying the data from grid to grid but rather from table to table. Assuming that you have DataTable1 bound to BindingSource1 bound to DataGridView1, and also BindingSource2 bound to DataGridView2 it would look like thisBig Smileim DataTable2 As DataTable = DataTable1.Clone()

    For Each row As DataGridViewRow In DataGridView1.SelectedRows
    DataTable2.ImportRow(DirectCast(row.DataBoundItem, DataRowView).Row)
    Next row

    BindingSource2.DataSource = DataTable2

     

    aldrean

    Mar 26th, 2007, 08:37 PM

    Thanks Jm, your post is highly appreciated.To give you some info, I had only my first DataGridView(dgvMain) that is bounded from my bindingSource.The second grid is just like a mirror of all the selected cells in my first grid, that is the reason why I did not intend to bound the second grid from another bindingSource.

    And one more thing, I am using DataSet in filling my Grid.

     

    aldrean

    Mar 26th, 2007, 09:27 PM

    At last I finally figure it out, with a great help from jmcilhinney still.Here's what I've got.
    Dim myTable As DataTable = Me.myDataSet.Tables(0)
    myTable.Clear()
    For Each row As DataGridViewRow In Me.dgvMain.SelectedRows
    myTable.ImportRow(DirectCast(row.DataBoundItem, DataRowView).Row)
    Next row

    Me.myBindingSource.DataSource = myTable

     

     

     

    Wednesday, August 20, 2008 7:56 AM
  • Hi Princy_Jones,

     

    My above code snippet isn't good enough to be used in your scenario.It is the best option to modify it based on your scenario. First you need to know if you don't select the whole data row, just some independent cells, how you modify the second datagridview control. I don't know your application logic. I think that you can use the DataGridView1.SelectedCells to know all selected cells in the one datagridview. In this scenario you use databinding to bind the datatable to the datagridview. Actually you can modify the underlying datatable object for the other datagridview for this issue. Read the following links for your reference:

     

    1. Manipulating Data in a DataTable. How to add, view, edit, and delete data in the table; how to monitor errors and events and query the data in the table.

     

    2. DataGridView Control (Windows Forms). The topics in this section describe the concepts and techniques that you can use to build DataGridView features into your applications.

     

    Best regards,

    Riquel

    Thursday, August 21, 2008 5:51 AM
    Moderator
  • Hi Riquel,

     

    Thanks alot again for your help, i finally got it, it was something like this....

     

    Code Snippet

    Dim val1 As

    String

    Dim val2 As String

    Dim val3 As Integer

    Dim val4 As Integer

    Dim Quantity As String

    Dim Check As Boolean

    Dim intPrice As Integer

    Dim intQuantity As Integer

    Dim intSum As Integer

    Dim intNewQty As Integer

    Check = False

    For Each row As DataGridViewRow In Me.DataGridView1.SelectedRows

    val1 = row.Cells(0).Value

    val2 = row.Cells(1).Value

    val3 = row.Cells(2).Value

    val4 = row.Cells(3).Value

    While Check = False

    Quantity = InputBox("Please enter the quantity")

    If Quantity = "" Then

    Exit Sub

    End If

    If IsNumeric(Quantity) Then

    Check = True

    End If

    End While

    Me.txtPrice.Text = val4

    Me.txtQuantity.Text = Quantity

    intPrice = txtPrice.Text

    intQuantity = txtQuantity.Text

    intSum = intPrice * intQuantity

    txtSum.Text = Convert.ToInt32(intSum)

    intNewQty = val3 - intQuantity

    Me.txtNewQtyOnHand.Text = Convert.ToInt32(intNewQty)

    Me.DataGridView2.Rows.Insert(0, val1, val2, Quantity, val4, intSum)

    Next

     

     

    i really couldn't jus seem to get it right the way i had searched for it!

    Anyway, i fianlly got that right, but i'm having problems updating my access database, as i need to update 3 tables from 2 screens and also update a table from a datagridview and textboxes! 

    Do you know if i should jus use the .update function or would i have to like create new rows in the table and than add tha data?

     Do have any good links i can read up on for updating?

     

    Thanks,

    Princy_Jones

     

     

     

     

    Thursday, August 21, 2008 3:54 PM
  • Hi Princy_Jones,

     

    You can read the ADO.NET tutorial for your reference. There is one section Retrieving and Modifying Data in ADO.NET about saving the data to the database. Also read this tutorial by ReneeC. It shows the whole code sample and explanation for working with the database.

     

    Best regards,

    Riquel

    Friday, August 22, 2008 1:48 AM
    Moderator