0 Replies - 736 Views - Last Post: 17 April 2014 - 05:41 AM

#1 thava  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 180
  • View blog
  • Posts: 1,606
  • Joined: 17-April 07

Copy and paste in data grid view with insert option

Posted 17 April 2014 - 05:41 AM

Appears there are lots of copy paste functions available for datagridview over the internet, but this one just helps you to enter a new record in a specified position I am just forming it within a keyboard event, you can carry it to the context menu click event also
Just copy and paste the following code in your Module
   Public Sub PasteTextDataFromClipboard(sender As System.Object, e As System.Windows.Forms.KeyEventArgs)
        'Pater the Data From clipboard
        If e.Control AndAlso e.KeyCode = Keys.V Then
            Try
                Dim Dgv As DataGridView = sender
                'Get the Data from the clipBoard as Text
                Dim s As String = Clipboard.GetText()
                'This is where we do our data split logic(i.e) how the data will paste in to the  Grid
                'since we get the data from from clipboard as text  we consider each data is seperated by Tab and each row is seperated by new line charecter
                'Get seperate lines
                Dim lines As String() = s.Split(New Char(1) {ControlChars.Cr, ControlChars.Lf}, StringSplitOptions.RemoveEmptyEntries)
                Dim bs As BindingSource = CType(Dgv.DataSource, BindingSource)

                Dim T As Type
                Dim Typename As String
                'Get the typename from the bining source
                Try
                    Typename = bs.DataSource.FullName()
                Catch ex As Exception
                    Try
                        Typename = bs.DataSource(0).GetType.FullName
                    Catch ex1 As Exception
                        Try
                            Typename = bs.DataSource.GetType.FullName
                        Catch ex2 As Exception
                            Typename = ""
                        End Try
                    End Try
                End Try
                'Create a Type from the TypeName
                If Typename = "" Then
                    MessageBox.Show("problem in Data type ")
                    Exit Sub
                End If
                T = Type.GetType(Typename)
                'Get the current row index where we need to paste the  data
                'The data is pasted from the selected row not from selected column 
                Dim RowIndex As Integer = Dgv.CurrentRow.Index
                Dim Lcount As Integer = lines.Count
                Dim overwrite As DialogResult
                'Ask the user to overwirte the Existing Data or just paste in as new row
                'you may extend or remove this logic here?
                If Not (Dgv.CurrentCell.Value Is Nothing Or Dgv.CurrentCell.Value.ToString = String.Empty) Then
                    overwrite = MessageBox.Show("Are you sure to overwirte the current value", sender.parent.Text, MessageBoxButtons.YesNo)
                Else
                    overwrite = Windows.Forms.DialogResult.No
                End If
                Dim counter As Integer = 0
                'Loop through all the pasted lines
                While counter < Lcount
                    'Check whether a new row is needed to insert inside a gridview
                    If overwrite = Windows.Forms.DialogResult.No OrElse (Dgv.Rows.Count - 1) <= RowIndex Then
                        'Check whether the data is binded by Datatable or Not able to find the base type
                        If T Is Nothing OrElse Typename.Contains("System.Data") OrElse T.BaseType.FullName.Contains("System.Data") Then
                            Dim obj As Object
                            With CType(sender.DataSource, BindingSource)
                                Dim tbl As DataTable
                                If Typename.Contains("View") Then                   'For DataView
                                    tbl = CType(.DataSource, DataView).Table
                                ElseIf Typename.Contains("DataSet") Then            'For DataSet
                                    tbl = CType(.DataSource, DataSet).Tables(sender.DataMember)
                                ElseIf Typename.Contains("Table") OrElse _
                                       T.BaseType.FullName.Contains("DataRow") Then 'For DataTable or TypeDataset
                                    tbl = CType(.DataSource, DataTable)
                                Else
                                    If bs.AllowNew = False Then
                                        MessageBox.Show("Not able to insert new records")
                                        Exit Sub
                                    End If
                                    obj = .AddNew
                                    RowIndex = .Count - 1
                                End If
                                'Tbl is nothing then it is not possible to be add a Datarow to underlying Datasource
                                If tbl IsNot Nothing Then
                                    obj = tbl.NewRow
                                    tbl.Rows.InsertAt(obj, RowIndex)
                                End If

                            End With

                        Else
                            'if it is an object source
                            'since we are uing BindingSource if we insert a object in the binding source it will
                            'Automatically insert a row in the Grid
                            With CType(Dgv.DataSource, BindingSource)
                                'Activator.CreateInstance create a new object for the given type
                                .Insert(RowIndex, Activator.CreateInstance(T))
                            End With
                        End If
                    End If
                    'choose the  Relative line
                    Dim line As String = lines(counter)
                    'split Data in a single line and iterate it
                    Dim cells As String() = line.Split(ControlChars.Tab)
                    'Fill the data by looping through the values
                    For j = 0 To Math.Min(cells.Count - 1, Dgv.Columns.GetColumnCount(DataGridViewElementStates.Visible) - 1)
                        Dgv.Item(j, RowIndex).Value = cells(j)
                    Next
                    RowIndex += 1
                    counter += 1
                End While
            Catch Pasteex As Exception
                MessageBox.Show(Pasteex.Message)
            End Try
        End If
    End Sub


Now add the following code in the form load event for your grid
AddHandler DataGridView1.KeyDown, AddressOf PasteTextDataFromClipboard


I think there is enough comments in the Code itself if you need more explanation feel free to ask

This post has been edited by thava: 17 April 2014 - 05:52 PM


Is This A Good Question/Topic? 0
  • +

Page 1 of 1