Results 1 to 8 of 8

Thread: [RESOLVED] SqlBulkCopy from DataGridView

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2010
    Location
    UK
    Posts
    288

    Resolved [RESOLVED] SqlBulkCopy from DataGridView

    I have a .csv file that is selected using the OpenFileDialog that then populates a DataGridView. The .csv file is then visible for the user to check a number of things. This part works fine.

    What I then need is once it is checked the user then needs to click a button to import this into my SQL Server table (CSV_Import). I have looked at SQLBulkCopy but am failing to get the data imported.

    Here is some code I have picked up and I am guessing that it is the bc.WriteToServer(dt) needs correcting within the brackets but I am at a loss at this point.

    bc.BatchSize = dt.Rows.Count
    bc.DestinationTableName = "CSV_Import"
    bc.WriteToServer(dt)

    bc.Close()
    myConnection.Close()

    Please advise, thanks.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: SqlBulkCopy from DataGridView

    We could guess, but wouldn't it make more sense for you to tell us what actually happens when you run that code? If there's an error then there's an error message, provided as an aid to diagnosing the issue. If you want us to diagnose the issue then it would make sense to pass that aid on to us.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2010
    Location
    UK
    Posts
    288

    Re: SqlBulkCopy from DataGridView

    Fair point and it may have been misleading what I have written.

    If I run the code it comes up wth no error because it is not picking up any data. I picked this piece of code up from the net and am not sure if that is what I need or not.

    I have data in a datagrid table that I want to import into a SQL Server table. I was told to use SQL BulkCopy. But I dont know what I am meant to do with it or how it works so if anyone can guide me through it that would be great.

    My datagridview has 4 to 18 coloumns and populates fine with the csv file. The table I want to import this data into has 18 columns which is the maximum number it would be.

    The user will click the button to import the data to the table. So on the click event I need to run sql bulkcopy.

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: SqlBulkCopy from DataGridView

    Right then. In that code, 'dt' is a DataTable. You need to populate a DataTable. The obvious option is to use ADO.NET to read your CSV file straight into a DataTable and then bind that to the grid. Any edits the user makes are then pushed to the DataTable automatically.

    Follow the Database FAQ link in my signature and check out some of the ADO.NET resources there see how to populate a DataTable. Note that you will use an OleDbDataAdapter and you can find the appropriate connection string for a CSV file at www.connectionstrings.com. Once populate, assign the Datatable to the DataSource of the grid to auto-populate it.

    I think you'll find that you need to set the AcceptChangesDuringFill property of the adapter to False too, although I could be wrong about that.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2010
    Location
    UK
    Posts
    288

    Re: SqlBulkCopy from DataGridView

    That may be obvious to you but not to me.

    If I can read the CSV file into the DataTable I would then be able to copy that using the bc.WriteToServer(dt) code.

    Can you advise how I populate the table with the csv file?

  6. #6
    Master Of Orion ForumAccount's Avatar
    Join Date
    Jan 2009
    Location
    Canada
    Posts
    2,802

    Re: SqlBulkCopy from DataGridView

    How are you currently loading the file? I believe what jmcilhinney is getting at, is use an OleDbDataAdapter and fill a DataTable object. You will need to specify the a) command text (aka "SELECT * FROM FileName.txt") and b) the connection string which can be retrieved here.

  7. #7
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: SqlBulkCopy from DataGridView

    How did you get it into the GDV in the first place?

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  8. #8

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2010
    Location
    UK
    Posts
    288

    Re: SqlBulkCopy from DataGridView

    Ok Ive done it. Here is the code on the button click event.

    I have a datagridview and button on the form. By clicking the button this then imports data into a table that is already there with the maximum number of fields ever needed.

    Thanks you all.
    vb Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.  
    3.         Dim myConnectionString As String = "Data Source=localhost;Initial Catalog=BulkIt;User Id=sa;"
    4.         Dim myConnection As SqlConnection = New SqlConnection(myConnectionString)
    5.         Dim csvInputFile As String = "C:\ Test\Bulk Import\filetest1.csv"
    6.  
    7.         Dim dt As New DataTable()
    8.         Dim line As String = Nothing
    9.         Dim i As Integer = 0
    10.  
    11.         Using sr As StreamReader = File.OpenText(csvInputFile)
    12.             line = sr.ReadLine()
    13.             Do While line IsNot Nothing
    14.                 Dim data() As String = line.Split(","c)
    15.                 If data.Length > 0 Then
    16.                     If i = 0 Then
    17.                         For Each item In data
    18.                             dt.Columns.Add(New DataColumn())
    19.                         Next item
    20.                         i += 1
    21.                     End If
    22.                     Dim row As DataRow = dt.NewRow()
    23.                     row.ItemArray = data
    24.                     dt.Rows.Add(row)
    25.                 End If
    26.                 line = sr.ReadLine()
    27.                 DataGridView1.DataSource = dt
    28.             Loop
    29.  
    30.         End Using
    31.  
    32.         myConnection.Open()
    33.         Dim bc As New SqlBulkCopy(myConnection)
    34.  
    35.         MsgBox(dt.Rows.Count)
    36.  
    37.         bc.BatchSize = dt.Rows.Count
    38.         bc.DestinationTableName = "CDR_Import"
    39.         bc.WriteToServer(dt)
    40.  
    41.         bc.Close()
    42.         myConnection.Close()
    43.  
    44.  
    45.  
    46.         DataGridView1.DataSource = dt
    47.  
    48.  
    49.     End Sub

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width