Not able to show matched data from database in listview - vb.net

Dim i As Integer
Dim itm As ListViewItem
Dim str(7) As String
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim Errors As String
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "Trojans.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
Errors = ""
For i = 1 To 4
Dim di As New DirectoryInfo(path(i))
For Each File In System.IO.Directory.GetFiles(path(i), "*", SearchOption.AllDirectories)
Dim fs As New FileInfo(File)
Label4.Text = fs.FullName
TextBox4.Text = _Info.mdsc(fs.FullName).ToUpper
Try
Using myConnection As OleDbConnection = New OleDbConnection(connString)
myConnection.Open()
Dim strg As String
strg = "SELECT * FROM Table1 WHERE MD5='" & TextBox4.Text
Using cmd2 As OleDbCommand = New OleDbCommand(strg, myConnection)
cmd2.Parameters.AddWithValue("MD5", TextBox4.Text)
Using dr As OleDbDataReader = cmd2.ExecuteReader
If dr.HasRows Then
dr.Read()
If TextBox4.Text = dr("MD5").ToString Then
Dim show As String = "SELECT * FROM Table1 WHERE MD5='" & TextBox4.Text
Label10.Text = Label10.Text + 1
str(0) = fs.Name
str(1) = show
str(2) = _Info.getSHA1Hash(fs.FullName)
str(3) = _Info.getSHA256Hash(fs.FullName)
str(4) = _Info.GetCRC32(fs.FullName)
str(5) = fs.FullName
str(6) = NativeMethods.FormatBytes(fs.Length) & " (" & fs.Length & " bytes)"
itm = New ListViewItem(str)
ListView1.Items.Add(itm) 'Added this but still no go
MsgBox("Found: " & dr("MD5") & "!")
Else
MsgBox("Error")
End If
Else
MsgBox("Error")
End If
End Using
End Using
End Using
Catch ex As Exception
'MsgBox(ex.ToString)
End Try
Label5.Text += 1
If Label5.Text < ProgressBar1.Maximum Then
ProgressBar1.Value = Label5.Text
End If
Next
Next
myConnection.Close()
I am trying to search a path,hash a file and show current hash in textbox4 at the same time searching ms database for the hash and if its their show corresponding info from database to list-view. Everything works ok except it does not add the data that is matched to list view.

Related

System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'

System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'
I have this error in this code how can I solve it?
Imports System.Data.OleDb
Public Class yenikayit
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim isimT As String = ""
Dim soyisimT As String = ""
Dim tcNoT As String = ""
Dim yasT As String = ""
Dim cinsiyetT As String = ""
Dim perNoT As String = ""
Dim egDurT As String = ""
Dim meslekT As String = ""
Dim telNoT As String = ""
Dim emailT As String = ""
isimT = TextBox1.Text
soyisimT = TextBox2.Text
tcNoT = TextBox3.Text
yasT = TextBox6.Text
cinsiyetT = ComboBox1.Text
perNoT = TextBox4.Text
egDurT = ComboBox2.Text
telNoT = TextBox5.Text
meslekT = TextBox10.Text
emailT = TextBox9.Text
Dim query As String = "INSERT INTO Personel (isim,soyisim,Yas,Cinsiyet,Alan,Egitim,TC,personel_id,tel_no,email) VALUES(isimT,soyisimT,yasT,cinsiyetT,meslekT,egDurT,tcNoT,perNoT,telNoT,emailT)"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\MONSTER\Desktop\AGKS\AGKS\Database5.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Dim sonuc As Boolean
sonuc = cmd.ExecuteNonQuery()
If (sonuc = 1) Then
MsgBox("Girdiğiniz veriler kayıt olmuştur")
conn.Close()
End If
End Sub
End Class
this is the part of the code that give us error
Currently, your code does not add any parameter values to the command, hence the "No Values Given" error. The command doesn't recognize those names and assign them values just because you have declared them as variables above. You should make it clear that those are parameters in your sql query, and then set each parameter's value before executing the query:
Note that all instances of OleDbType.VarChar need to be replaced with the correct datatypes of your columns. I obviously have no way of knowing what types those columns are so I have just made them all VarChar, but you should adjust those to match your table schema.
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\MONSTER\Desktop\AGKS\AGKS\Database5.accdb"
Dim query As String = "INSERT INTO Personel (isim,soyisim,Yas,Cinsiyet,Alan,Egitim,TC,personel_id,tel_no,email) " & _
"VALUES (#isimT,#soyisimT,#yasT,#cinsiyetT,#meslekT,#egDurT,#tcNoT,#perNoT,#telNoT,#emailT)"
Using conn As OleDbConnection = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
With cmd
.Parameters.Add("#isimT", OleDbType.VarChar).Value = TextBox1.Text
.Parameters.Add("#soyisimT", OleDbType.VarChar).Value = TextBox2.Text
.Parameters.Add("#yasT", OleDbType.VarChar).Value = TextBox6.Text
.Parameters.Add("#cinsiyetT", OleDbType.VarChar).Value = ComboBox1.Text
.Parameters.Add("#meslekT", OleDbType.VarChar).Value = TextBox10.Text
.Parameters.Add("#egDurT", OleDbType.VarChar).Value = ComboBox2.Text
.Parameters.Add("#tcNoT", OleDbType.VarChar).Value = TextBox3.Text
.Parameters.Add("#perNoT", OleDbType.VarChar).Value = TextBox4.Text
.Parameters.Add("#telNoT", OleDbType.VarChar).Value = TextBox5.Text
.Parameters.Add("#emailT", OleDbType.VarChar).Value = TextBox9.Text
End With
conn.Open()
Dim sonuc As Boolean
sonuc = cmd.ExecuteNonQuery()
If (sonuc = 1) Then
MsgBox("Girdiğiniz veriler kayıt olmuştur")
End If
conn.Close()
End Using
Ok, try something like this:
Dim query As String = "INSERT INTO Personel (isim,soyisim,Yas,Cinsiyet,Alan,Egitim,TC,personel_id,tel_no,email) "
query +="VALUES(#isimT,#soyisimT,#yasT,#cinsiyetT,#meslekT,#egDurT,#tcNoT,#perNoT,#telNoT,#emailT)"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\MONSTER\Desktop\AGKS\AGKS\Database5.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
query.Parameters.AddWithValue("#isimT", TextBox1.Text)
cmd.Parameters.AddWithValue("#soyisimT", TextBox2.Text)
cmd.Parameters.AddWithValue("#tcNoT", TextBox3.Text)
cmd.Parameters.AddWithValue("#yasT", TextBox6.Text)
cmd.Parameters.AddWithValue("#cinsiyetT", ComboBox1.Text)
cmd.Parameters.AddWithValue("#perNoT", TextBox4.Text)
cmd.Parameters.AddWithValue("#egDurT", ComboBox2.Text)
cmd.Parameters.AddWithValue("#telNoT", TextBox5.Text)
cmd.Parameters.AddWithValue("#meslekT", TextBox10.Text)
cmd.Parameters.AddWithValue("#emailT", TextBox9.Text)
conn.Open()
Dim sonuc As Boolean
sonuc = cmd.ExecuteNonQuery()
If (sonuc = 1) Then
MsgBox("Girdiğiniz veriler kayıt olmuştur")
conn.Close()
End If
This should do the job. This should fix your exception.

Comparing TimeoftheDay to a String

Error in Comparing Time to a String
Cdate is my previous code and i revise it to compareTime Can anyone
help me if the current expression to compare time is correct because
the message is "Contact your Administrator! Maybe your not
registered."
So the expression is still "false"
#Region "TIMER"
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
LBLDATE.Text = My.Computer.Clock.LocalTime.Date
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
LBLTIME.Text = TimeOfDay
End Sub
#End Region
Dim conn As OleDb.OleDbConnection = GetConnection()
Dim sql As String
Dim sql1 As String
Dim A As Integer
Dim result = Nothing
Dim compareTime As String = "7:01:00 PM"
' Dim amlate1 As String = "7:01:00 PM"
Dim remm1 As String
' If CDate(Form7TO3.LBLTIME.Text) >= CDate(amlate1) Then
If compareTime = DateTime.Now.ToString("h:mm:ss tt") Then
remm1 = "LATE"
Else
remm1 = "ON TIME"
End If
Try
sql1 = "SELECT * FROM DTR_REC WHERE MEM_CODES LIKE '" & Form7TO3.txtinput.Text & "' AND SDATE = '" & Form7TO3.LBLDATE.Text & "'"
Dim DA As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sql1, conn)
Dim DS As New DataSet
DA.Fill(DS, "dtrdb")
A = DS.Tables("dtrdb").Rows.Count
If A > 0 Then
MessageBox.Show("Sorry you Already finished Log in!")
Else
sql = "INSERT INTO DTR_REC (MEM_CODES, AM_IN, FIRST_AM_REMARK, SDATE) VALUES (#MEM_CODES, #AM_IN, #FIRST_AM_REMARK, #SDATE)"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDb.OleDbParameter("#MEM_CODES", Form7TO3.txtinput.Text))
cmd.Parameters.Add(New OleDb.OleDbParameter(" #AM_IN", Form7TO3.LBLTIME.Text))
cmd.Parameters.Add(New OleDb.OleDbParameter("#FIRST_AM_REMARK", remm1))
cmd.Parameters.Add(New OleDb.OleDbParameter("#SDATE", DateTime.Parse(Form7TO3.LBLDATE.Text)))
conn.Open()
cmd.ExecuteNonQuery()
If remm1 = "LATE" Then
MessageBox.Show("Hurry up your Late")
ElseIf remm1 = "ON TIME" Then
MessageBox.Show("Very good you come on time!")
End If
End If
clear()
Catch ex As Exception
Dim dgresult As DialogResult
Dim ms As String
ms = "Contact your Administrator! Maybe your not registered."
MessageBox.Show(ms, "Error in connection", MessageBoxButtons.OKCancel, _
MessageBoxIcon.Stop, MessageBoxDefaultButton.Button2)
If dgresult = DialogResult.Yes Then
Form1.Show()
End If
End Try
Return result
Here's my current codes
Can anyone revise this codes
If the record is already exist a messagebox will appear saying "Sorry you finished log in"
otherwise it will save/add records on my database
(The problem is , if the records still exists it add/insert another the same record)
Dim conn As OleDb.OleDbConnection = GetConnection()
Dim sql As String
Dim sql1 As String
'Dim A As Integer
Dim result = Nothing
'Dim time_1 As String = DateTime.Parse("11:00:00 PM").ToString("T")
'Dim time_2 As String = DateTime.Now.ToString("T")
Dim remm1 As String
Dim PMOUT As String = "11:00:00 PM"
Dim str As String = "HH:mm:ss"
str = TimeOfDay()
' If DateTime.Now.TimeOfDay > amlate1.TimeOfDay Then
' If DateTime.Compare(time_1, time_2) > 0 Then
If str >= PMOUT Then
remm1 = "LATE"
Else
remm1 = "ON TIME"
End If
Try
conn.Open()
sql1 = "SELECT * FROM DTR_REC WHERE MEM_CODES = '" & Form11TO7.txtinput.Text & "' AND SDATE = #" & FormatDateTime(DateTime.Now, DateFormat.GeneralDate = DateFormat.ShortDate) & "#"
' Dim DA As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sql1, conn)
Dim cmd1 As New OleDb.OleDbCommand(sql1, conn)
'Dim DS As New DataSet
'DA.Fill(DS, "dtrdb")
'A = DS.Tables("dtrdb").Rows.Count
'If A > 0 Then
Using reader As OleDb.OleDbDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
'user already finished to time in
MessageBox.Show("Sorry you Already finished Log in!")
Else
sql = "INSERT INTO DTR_REC (MEM_CODES, PM_IN, FIRST_PM_REMARK, SDATE) VALUES (#MEM_CODES, #PM_IN, #FIRST_PM_REMARK, #SDATE)"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDb.OleDbParameter("#MEM_CODES", Form11TO7.txtinput.Text))
cmd.Parameters.Add(New OleDb.OleDbParameter(" #PM_IN", str))
cmd.Parameters.Add(New OleDb.OleDbParameter("#FIRST_PM_REMARK", remm1))
cmd.Parameters.Add(New OleDb.OleDbParameter("#SDATE", FormatDateTime(DateTime.Now, DateFormat.GeneralDate = DateFormat.ShortDate)))
Dim icount As String
icount = cmd.ExecuteNonQuery()
MessageBox.Show(icount)
If remm1 = "LATE" Then
MessageBox.Show("Hurry up your Late")
ElseIf remm1 = "ON TIME" Then
MessageBox.Show("Very good you come on time!")
End If
End If
End Using
clear()
Catch ex As Exception
Dim dgresult As DialogResult
Dim ms As String
ms = "Contact your Administrator! Maybe your not registered."
'MessageBox.Show(ms = "Contact your Administrator! Maybe your not registered." & vbNewLine & ex.Message)
MessageBox.Show(ms, "Error in connection", MessageBoxButtons.OKCancel, _
MessageBoxIcon.Stop, MessageBoxDefaultButton.Button2)
If dgresult = DialogResult.Yes Then
Form1.Show()
End If
'MessageBox.Show(ex.Message)
End Try
Return result

Input array is longer than the number of columns

In the event dragdrop of a datagridview I got this error:
Here's the whole code of my dragdrop event :
Private Sub DataGridView1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop
Dim clientPoint As Point = DataGridView1.PointToClient(New Point(e.X, e.Y))
Dim hit As DataGridView.HitTestInfo = DataGridView1.HitTest(clientPoint.X, clientPoint.Y)
Dim dgvr As DataGridViewRow = DirectCast(e.Data.GetData(GetType(DataGridViewRow)), DataGridViewRow)
Dim celldata As Object() = New Object(dgvr.Cells.Count) {}
For col As Integer = 0 To dgvr.Cells.Count - 1
celldata(col) = dgvr.Cells(col).Value
Next
Dim dt As New DataTable()
dt = ds_data.Tables(0)
Dim colCheckbox As DataColumn = dt.Columns.Add("Column1", GetType(Boolean))
Dim row As DataRow = dt.NewRow()
row.ItemArray = celldata
dt.Rows.InsertAt(row, hit.RowIndex)
dgvr.DataGridView.Rows.Remove(dgvr)
Dim sqlCmd As SqlCommand
sqlCmd = con.CreateCommand()
sqlCmd.CommandText = "update megatom_data_commande set ordre='" & hit.RowIndex & "' where id='" & DataGridView1.Rows(hit.RowIndex).Cells("ID").Value.ToString & "'"
Try
sqlCmd.ExecuteNonQuery()
DataGridView2.DataSource = ds_data2.Tables(0).DefaultView
DataGridView1.DataSource = ds_data.Tables(0).DefaultView
Dim CMD As New SqlCommand("PLANNIFIER")
CMD.Parameters.Add("#CHAINE", SqlDbType.VarChar).Value = cboChaine.SelectedItem.ToString
ExecuteCMD(CMD)
Catch ex As SqlException
End Try
End Sub
In fact my datatable have 15 columns but I added manually a checkbox column to select rows so I think i have a problem of indexes but I dont know how to resolve that problem.
My ds_data is defined like the code below:
requestPlanifie = "select megatom_data_commande.id as ID,numéro,observation,moule,commande,id_etat,programme,ordre,moule,glav,Qté_commandée_Totale," _
& " Qté_coupée_cuir, Qté_coupée_synthétique, Qté_piquée, Qté_finie from megatom_data_commande" _
& " inner join dbo.MEGATOM_DATA_MOULE on megatom_data_moule.id=megatom_data_commande.id_moule " _
& " where id_chaine='" & cboChaine.Text & "' and ( id_etat='3' or id_etat='4') order by numéro asc,ordre asc"
Dim dataAdapter As New SqlDataAdapter(requestPlanifie, con)
Try
dataAdapter.Fill(ds_data, "ds_data")
dataAdapter2.Fill(ds_data2, "ds_data2")
Catch ex As SqlException
End Try
DataGridView1.DataSource = ds_data.Tables(0).DefaultView

Search through the database using a combobox, if an item is in a database, prompt will appear

Good day everyone.
I'm making a POS and Inventory Management System and I'm having a problem with this particular module as of now.
When adding an item to purchase order list, if an item is already in the purchaseorder database, the system will prompt that there is already a pending order. I've done the prompt, but the adding to the database was kinda messed up. It doesn't do a thing at all. The code there is working when I remove the ds.hasrows and while dr.read conditions. This is my code:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Ceiling = CInt(txtCeiling.Text)
TotalQuantity = CurrentItemQuantity + CInt(txtPurchaseQty.Text)
If TotalQuantity > Ceiling Then
MsgBox("Exceeds Ceiling Point.")
Else
sqlString = "SELECT PRODUCT_ID FROM posinventory.purchaseorder WHERE purchaseorder.PRODUCT_ID = '" & cboProductID.Text & "'"
cmd = New MySqlCommand(sqlString, con)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
If CurrentItem = dr.Item("PRODUCT_ID") Then
MsgBox("Product has pending order.")
cboProductID.Focus()
Else
sqlString = "INSERT INTO posinventory.purchaseorder (PRODUCT_ID, PURCHASE_QUANTITY, DATE_PURCHASED, TIME_PURCHASED) VALUES (" & cboProductID.Text & ", '" & txtPurchaseQty.Text & "', '" & txtDate.Text & "', '" & txtTime.Text & "')"
Try
cmd = New MySqlCommand(sqlString, con)
dr = cmd.ExecuteReader
dr.Close()
Catch ex As Exception
MsgBox("Error saving to database. Error is: " & ex.Message)
Exit Sub
End Try
MsgBox("Transaction Complete.")
lvOrderList.Items.Clear()
sqlString = "SELECT posinventory.purchaseorder.TRANSACTION_ID, posinventory.products.PRODUCT_ID, posinventory.products.PRODUCT_NAME, posinventory.products.SUPPLIER_NAME, posinventory.purchaseorder.PURCHASE_QUANTITY, posinventory.purchaseorder.DATE_PURCHASED, posinventory.purchaseorder.TIME_PURCHASED FROM posinventory.purchaseorder, posinventory.products WHERE posinventory.purchaseorder.PRODUCT_ID = posinventory.products.PRODUCT_ID"
cmd = New MySqlCommand(sqlString, con)
da = New MySqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcol(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcol)
Me.lvOrderList.Items.Add(lvi)
Next
grpCreateOrder.Enabled = False
grpOrderList.Enabled = True
cboProductID.SelectedIndex = -1
txtPurchaseQty.Text = ""
txtDate.Text = ""
txtTime.Text = ""
txtProductName.Text = ""
txtSupplier.Text = ""
txtQty.Text = ""
txtCeiling.Text = ""
btnBack.Enabled = True
End If
End While
End If
dr.Close()
End If
End Sub
I think its because you are inside of a loop using a cmd and dr. While you are in there you are then defining a new cmd and dr.
Try using different names eg cmd2, dr2.

failed to read the excel to sql database

I want to upload an Excel file and write data to sql server 2008.
The Excel file has 7 sheets and it writes in 7 tables.
Example : (sheetn -> temp_sheetn)
The code is working well but the last sheet is not writing in the last table.
The code is like this:
Partial Class app_UploadData
Inherits System.Web.UI.Page
Dim apps As New MyApps
Dim GlobReg As Integer = 0
Dim GlobOTC As Integer = 0
Private dt As DataTable = Nothing
Public Function xlsInsert(ByVal pth As String) As System.Data.DataTable
Dim strcon As String = String.Empty
If Path.GetExtension(pth).ToLower().Equals(".xls") OrElse Path.GetExtension(pth).ToLower().Equals(".xlsx") Then
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & pth & ";Extended Properties=""Excel 8.0;HDR=YES;"""
Else
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & pth & ";Extended Properties=""Excel 12.0;HDR=YES;"""
End If
Dim strselect As String = "Select * from [Sheet1$]"
Dim exDT As New DataTable()
Using excelCon As New OleDbConnection(strcon)
Try
excelCon.Open()
Using exDA As New OleDbDataAdapter(strselect, excelCon)
exDA.Fill(exDT)
End Using
Catch oledb As OleDbException
Throw New Exception(oledb.Message.ToString())
Finally
excelCon.Close()
End Try
For i As Integer = 0 To exDT.Rows.Count - 1
' Check if first column is empty
' If empty then delete such record
If exDT.Rows(i)("CardNo").ToString() = String.Empty Then
exDT.Rows(i).Delete()
End If
Next
exDT.AcceptChanges()
' refresh rows changes
If exDT.Rows.Count = 0 Then
Throw New Exception("File uploaded has no record found.")
End If
Return exDT
End Using
End Function
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim ds As New DataSet()
Dim XlsConnString As String = String.Empty
Dim DirPath As String = Server.MapPath("~/Temp_Upload/")
Dim fName As String
If (Directory.Exists(DirPath)) Then
For Each fName In Directory.GetFiles(DirPath)
If File.Exists(fName) Then
File.Delete(fName)
End If
Next
End If
If xlsUpload.HasFile Then
Dim fileName As String = Path.GetFileName(xlsUpload.PostedFile.FileName)
Dim fileExtension As String = Path.GetExtension(xlsUpload.PostedFile.FileName)
Dim fileLocation As String = Server.MapPath("~/Temp_Upload/" & fileName)
xlsUpload.SaveAs(fileLocation)
'Check whether file extension is xls or xslx
If fileExtension = ".xls" Then
XlsConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
ElseIf fileExtension = ".xlsx" Then
XlsConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
ElseIf fileExtension <> ".xls" Or fileExtension <> ".xlsx" Then
lblMessage.Text = "Upload file must be excel !"
Exit Sub
End If
Dim cmd As New SqlCommand : Dim SheetName As String 'Dim dr As SqlDataReader
'Dim tran As SqlTransaction
apps.OpenConnection()
cmd.Connection = apps.oConn
Dim cn As New OleDbConnection(XlsConnString)
Try
cn.Open()
Catch ex As OleDbException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
' It Represents Excel data table Schema.
Dim dt As New System.Data.DataTable()
dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt IsNot Nothing OrElse dt.Rows.Count > 0 Then
For sheet_count As Integer = 1 To dt.Rows.Count - 1
Try
' Create Query to get Data from sheet.
SheetName = dt.Rows(sheet_count)("table_name").ToString()
'Dim da As New OleDbDataAdapter("SELECT * FROM [" & sheetname & "]", cn)
'da.Fill(ds, sheetname)
'Execute a query to erase any previous data from our destination table
cmd.CommandText = "Truncate Table Temp_" & SheetName
cmd.ExecuteNonQuery()
'Series of commands to bulk copy data from the excel file into our SQL table
Dim OleDbConn As OleDbConnection = New OleDbConnection(XlsConnString)
Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [" & SheetName & "]"), OleDbConn)
'Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [Customer$]"), OleDbConn)
OleDbConn.Open()
Dim OleDbRead As OleDbDataReader = OleDbCmd.ExecuteReader()
Dim bulkCopy As SqlBulkCopy = New SqlBulkCopy(apps.oConn)
bulkCopy.DestinationTableName = "Temp_" & SheetName
bulkCopy.WriteToServer(OleDbRead)
OleDbConn.Close()
OleDbConn = Nothing
Catch ex As DataException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Next
End If
cn.Close()
cn = Nothing
apps.CloseConnection()
End If
End Sub
End Class
The line that reads
For sheet_count As Integer = 1 To dt.Rows.Count - 1
should either be
For sheet_count As Integer = 0 To dt.Rows.Count - 1
or
For sheet_count As Integer = 1 To dt.Rows.Count
The first one I suspect, but I can't remember if this is a zero based list as I haven't got VB.Net installed here.
Incidentally there's no need to check the file extension is .xls and then to use the Jet provider, Microsoft.ACE.OLEDB.12.0 will work just fine on .xls files.