?
Solved

COPY FROM EXCEL TO DATAGRIDVIEW THEN SAVE TO SQL

Posted on 2013-05-15
1
Medium Priority
?
511 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
[X]
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
1 Comment
 
LVL 16

Accepted Solution

by:
Rose Babu earned 2000 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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

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:…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
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…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …

770 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