Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all articles
Browse latest Browse all 27554

Import csv into database datatable via openfiledialog

$
0
0
I am using Visual Basic Express 2010. I have added a SQL Server Compact 3.5 Database, a Dataset and a Datatable with 11 columns. While setting this up, VBE 2010 posted a DataTableBindingSource, DataTableAdapter, DataTableBindingNavigator, and TableAdapterManager. I added a Windows Form2 and dragged the DataTable onto Form2.

From a button click on Form1, how can I openfiledialog, select a csv file with 11 columns, and import the values into the Database DataTable on Form2? The csv file will always have 11 columns but will vary in the number of rows from 1 to several hundred thousand. Any assistance would be appreciated.

I believe I have the correct code for Button1 on Form1:

Code:

Private Sub ToolStripButton1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click

        Dim openFileDialog1 As New OpenFileDialog()
        openFileDialog1.InitialDirectory = "c:\"
        openFileDialog1.Filter = "txt files (*.csv)|*.csv|All files (*.*)|*.*"
        openFileDialog1.FilterIndex = 1
        openFileDialog1.RestoreDirectory = True

        If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then

            Dim frm2 As New Form2(openFileDialog1.FileName)
            frm2.Show()


This is what I have so far on Form2 and where I am struggling to complete the code to load the datatable:

Code:

Imports System.IO
Imports System.Data.OleDb

Public Class Form2

    Public Sub New(ByVal fileName As String)

        InitializeComponent()

        Dim file As String = IO.Path.GetFileName(fileName)
        Dim path As String = IO.Directory.GetParent(fileName).FullName

        Try

            If IO.File.Exists(IO.Path.Combine(path, file)) Then
                Dim ConStr As String = _
                "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
                path & ";Extended Properties=""Text;HDR=No;FMT=Delimited\"""
                Dim conn As New OleDb.OleDbConnection(ConStr)
                Dim da As New OleDb.OleDbDataAdapter("Select * from " & _
                file, conn)


Viewing all articles
Browse latest Browse all 27554

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>