My program is written in VB.net 2005. My users routinely copy data from an Excel spreadsheet onto a datagridview inthe app. Theycopy via cntl-c on the source side and thenhighlight the desired destination cells in thedatagrid. Then theytrigger thepaste event by clicking on abutton in theUI.They may copy multiple rows and multiple columns at the same time. I check to see that the number of cells copied is equal to the number of datagrid cells highlighted before I do the paste.
The code is:
Private Sub PasteButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PasteButton.Click
Dim clipObject As IDataObject = Clipboard.GetDataObject()
Dim i As Integer
Dim DestinationOk As Boolean
DestinationOk = CheckSelectedCellCount() 'This just checks if > 0 cellsare highlighted
If Not DestinationOk Then
Return
End If
If Not clipObject Is Nothing Then
If (clipObject.GetDataPresent(DataFormats.CommaSeparatedValue)) Then
Dim sr As New IO.StreamReader( _
CType(clipObject.GetData(DataFormats.CommaSeparatedValue), IO.Stream))
Dim s As String = sr.ReadToEnd()
sr.Close()
Dim pasteArray(100)
'Parse for both commas and CrLf characters:
pasteArray = s.Split(New [Char]() {vbCrLf, ","})
Array.Reverse(pasteArray)
If P_DatagridView.SelectedCells.Count <> pasteArray.Length - 1 Then
MsgBox("Number of values to paste does not equal number of cells selected." & vbCrLf & "No action taken.")
Return
End If
For i = 0 To P_DatagridView.SelectedCells.Count - 1
P_DatagridView.BeginEdit(True)
P_DatagridView.SelectedCells(i).Value = pasteArray(i + 1).ToString
GetNewValues(P_DatagridView.SelectedCells(i).OwningRow)
P_DatagridView.EndEdit()
Next i
Else
MsgBox("No data in the clipboard to paste." & vbCrLf & "No action taken.")
End If
Else
MsgBox("No data in the clipboard to paste." & vbCrLf & "No action taken.")
End If
End Sub
This code works fine except when the data the users want to paste has embedded commas (within a single spreadsheet cell). When that is true, the code divides that data into separate destinations and returns the "Number of values to paste does not equal number of cells selected" error. Of course, I've tried to use other data formats besides csvfor the clipboard data but I get run-time errors. The data can be string, date,real and any combination of those datatypes.
Can anyone suggest how to capture the clipboard data and paste it across datagridview cells when it contains commas?
Thank you.