user8828022
user8828022

Reputation:

Pasting Cells from Excel into Datagridview VB.net

I have this code that i use to paste into my datagridview under the KeyDown event:

 If e.Control AndAlso e.KeyCode = Keys.V Then
        Try
            For Each line As String In Clipboard.GetText.Split(vbNewLine)
                If Not line.Trim.ToString = "" Then
                    Dim item() As String = line.Trim.Split(vbTab)
                    Me.Datagridview1.Rows.Add(item)
                End If
            Next

        Catch ex As Exception
            MessageBox.Show(ex.Message, My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End If

It works fine to paste data, the problem is when i paste blank cells in to the datagridview it ignores some of the blanks and shift the cells with content.

Example when i paste this:

            Column1 Column2 Column3 Column4
       Row1    a       b              d
       Row2            f       g

This is what i get:

            Column1 Column2 Column3 Column4
       Row1    a       b               d
       Row2    f       g

Does anyone know what could i be doing wrong or how to improve my code?

Upvotes: 1

Views: 7230

Answers (1)

PavlinII
PavlinII

Reputation: 1083

Change this

Dim item() As String = line.Trim.Split(vbTab(0))

to this

Dim item() As String = line.Split(vbTab(0))

or this, if you want to trim content of individual cells, but that's not good idea

Dim item() As String = line.Split(vbTab(0)).Select(Function(X) X.Trim).ToArray

That .Trim call is stripping the initial TAB from your line and shifts your data.

Upvotes: 2

Related Questions