Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

COPY FROM EXCEL TO DATAGRIDVIEW THEN SAVE TO SQL

Posted on 2013-05-15
1
500 Views
Last Modified: 2013-05-22
I want to copy from excel to a clipboard then paste into a datagridview   then save to SQL TABLE

to copy and PASTE to the clipboard I am using this code below which works fine

Dim strPasteText As String = Clipboard.GetText
        Dim strSplitter() As String = {vbCrLf}
        Dim strSplitterC() As String = {vbTab}
        Dim strRows() As String = strPasteText.Split(strSplitter, StringSplitOptions.RemoveEmptyEntries)
        Dim iRows As Integer = strRows.Length
        Dim strCells() As String = strRows(0).Split(strSplitterC, StringSplitOptions.None)
        Dim iCells As Integer = strCells.Length
       
        DataGridView3.RowCount = iRows
        DataGridView3.ColumnCount = iCells

        For iColCounter As Integer = 0 To iCells - 1
            DataGridView3.Columns(iColCounter).Name = strCells(iColCounter)
        Next

        DataGridView3.Rows(0).Selected = True

        For iRowCounter As Integer = 1 To iRows - 1
            strCells = strRows(iRowCounter).Split(strSplitterC, StringSplitOptions.None)

            For iCellCounter As Integer = 0 To iCells - 1
                DataGridView3.Rows(iRowCounter - 1).Cells(iCellCounter).Value = strCells(iCellCounter)
            Next
        Next




But the problem comes when I tried to bulk write  using
Dim dt As New DataTable
        dt = DataGridView3.DataSource
        Dim objSQLCon As New SqlConnection("Data Source=xxxxxxx;Initial Catalog=xxxxxx;Integrated Security=SSPI;User ID=xxxxr;Password=xxxxxxx")
        Dim TableName As String = "[xxxxxx].MASTERSCHEDULE"
        Dim strErrorMessage As String = ""

        Try

        Catch ex As Exception

        End Try
        If objSQLCon.State = ConnectionState.Open Then
            objSQLCon.Close()
        End If

        objSQLCon.Open()

        Try

        Catch ex As Exception

        End Try
        'To Perform Bulk Copy for copy data from DataTable to SQL Table
        If dt.Rows.Count > 0 Then
            Using Sqlbcp As SqlBulkCopy = New SqlBulkCopy(objSQLCon)
                Sqlbcp.DestinationTableName = "[xxxxxx]." & TableName & ""
                Sqlbcp.WriteToServer(dt)
            End Using
        End If

since there is not Datasource for DATAGRIDVIEW3  because is not databound
0
Comment
Question by:teogos
1 Comment
 
LVL 16

Accepted Solution

by:
Rose Babu earned 500 total points
ID: 39170997
Hi,

at the run-time only you have pasted the data to DataGridView. so at the beginning, the DataSource will be null.

and when you get the DataGridView's DataSource after you pasted the data, then also it will be empty.

to overcome this, loop the datagridview and load all the data into a datatable then use the updated datatable to bulkcopy process

Have a look on the updated code. this works well for me.

Dim dtUpdated = New DataTable
Dim drUpdated As DataRow
For Each col As DataGridViewColumn In DataGridView2.Columns
	dtUpdated.Columns.Add(col.Name)
Next

Dim j As Integer = 0

Dim r As New DataGridViewRow
' The footer new row is also adding as empty row. so i used DataGridView2.Rows.Count - 2. update it accordingly
For i = 0 To DataGridView2.Rows.Count - 2
	r = DataGridView2.Rows(i)

	drUpdated = dtUpdated.NewRow
	For Each cells As DataGridViewCell In r.Cells
		drUpdated(j) = cells.Value
		j = j + 1
	Next
	dtUpdated.Rows.Add(drUpdated)
	j = 0
Next

Dim objSQLCon As New SqlClient.SqlConnection("server=*********;Initial Catalog=*********;Integrated Security=SSPI;")
Dim TableName As String = "BulkCopyTest"
Dim strErrorMessage As String = ""

Try

	If objSQLCon.State = ConnectionState.Open Then
		objSQLCon.Close()
	End If

	objSQLCon.Open()


	'To Perform Bulk Copy for copy data from DataTable to SQL Table
	If dtUpdated.Rows.Count > 0 Then
		Using Sqlbcp As SqlClient.SqlBulkCopy = New SqlClient.SqlBulkCopy(objSQLCon)
			Sqlbcp.DestinationTableName = TableName
			Sqlbcp.WriteToServer(dtUpdated)
		End Using
	End If

	objSQLCon.Close()
Catch ex As Exception
	objSQLCon.Close()
End Try

Open in new window

0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

790 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question