How to import the data from excel to the .mdb access file? - vb.net

Here i m have some problem were export the data which in excel to the format of .mdb. i m trying the code were showing below, but it shows the messageBox
Import Failed, correct Column name in the sheet!
Error Message:
The 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine
is there anyone can help me.
Best Regards,
Thanes
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' delete the file with the same and create a new access file
If File.Exists("C:\Users\Admin\Desktop\test\CA\book.mdb") Then
File.Delete("C:\Users\Admin\Desktop\test\CA\book.mdb")
End If
Dim _accessData As Access.Application
_accessData = New Access.Application()
_accessData.Visible = False
_accessData.NewCurrentDatabase("C:\Users\Admin\Desktop\test\CA\book.mdb", Access.AcNewDatabaseFormat.acNewDatabaseFormatAccess2000, , , )
_accessData.CloseCurrentDatabase()
_accessData.Quit(Microsoft.Office.Interop.Access.AcQuitOption.acQuitSaveAll)
_accessData = Nothing
' initialize the connect string
Dim _filename As String = "C:\Users\Admin\Desktop\test\CA\test.xls"
Dim _conn As String
_conn = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Users\Admin\Desktop\test\CA\test.xls" & _filename & ";" & "Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
Dim _connection As OleDbConnection = New OleDbConnection(_conn)
'Use OledbCommand object to select all the data from sheet1 and execute an ExecuteNonQuery to import data into Book.mdb.
Dim _command As OleDbCommand = New OleDbCommand()
_command.Connection = _connection
Try
_command.CommandText = "SELECT * INTO [MS Access;Database=C:\Users\Admin\Desktop\test\CA\book.mdb].[Sheet1] FROM [Sheet1$A4:D]"
_connection.Open()
_command.ExecuteNonQuery()
_connection.Close()
MessageBox.Show("The import is complete!")
Catch e1 As Exception
MessageBox.Show("Import Failed, correct Column name in the sheet!" & Environment.NewLine & "Error Message:" & Environment.NewLine & e1.Message)
End Try
End Sub
*Note: the program is can create .mdb file, but cannot import the excel data into it.

i m settle it rdy...thank anyway for the help...
Public Class Form1
Private DBPath As String
Private conn As OleDbConnection
Public Sub New()
InitializeComponent()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
''delete the file with the same and create a new access file
If File.Exists("C:\Users\Inari Admin\Desktop\test\CA\test.mdb") Then
File.Delete("C:\Users\Inari Admin\Desktop\test\CA\test.mdb")
End If
DBPath = "C:\Users\Inari Admin\Desktop\test\CA\test.mdb"
' create DB via ADOX if not exists
' NOTE: to use ADOX add reference to COM Microsoft ADO Ext. 2.6 for DDL and Security!
If Not File.Exists(DBPath) Then
Dim cat As New ADOX.Catalog()
cat.Create(Convert.ToString("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=") & DBPath)
cat = Nothing
End If
conn = New OleDbConnection(Convert.ToString("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=") & DBPath)
conn.Open()
Try
Using cmd As New OleDbCommand("CREATE TABLE [test] ([id] COUNTER PRIMARY KEY, [num] INT, [name] MEMO, [no] INT);", conn)
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
If ex IsNot Nothing Then
ex = Nothing
End If
End Try
' initialize the connect string
Dim _filename As String = "C:\Users\Inari Admin\Desktop\test\CA\test.xls"
Dim _conn As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & _filename & ";" & "Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
Dim _connection As OleDbConnection = New OleDbConnection(_conn)
'Use OledbCommand object to select all the data from sheet1 and execute an ExecuteNonQuery to import data into test.mdb.
Dim _command As OleDbCommand = New OleDbCommand()
_command.Connection = _connection
Try
Using conn As New OleDbConnection(_conn)
Using cmd As New OleDbCommand()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO [MS Access;Database=" + DBPath + "].[test] SELECT * FROM [Sheet1$]"
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
'_command.CommandText = "SELECT * FROM [Sheet1$]"
'_connection.Open()
'_command.ExecuteNonQuery()
'_connection.Close()
MessageBox.Show("The import is complete!")
Catch e1 As Exception
MessageBox.Show("Import Failed, correct Column name in the sheet!" & Environment.NewLine & "Error Message:" & Environment.NewLine & e1.Message)
End Try
End Sub
End Class

Related

Update datagridview after delete something

I am trying to refresh my datagridview after delete something from database. The code that I am actually using on my delete button is
Private Sub cmdDelete_Click(sender As Object, e As EventArgs) Handles cmdDelete.Click
If txtDelete.Text <> "" Then
If MsgBox("Deseja apagar o ficheiro " & txtDelete.Text & "?", MsgBoxStyle.YesNo) Then
SQL.DataDelete("DELETE FROM infofile WHERE Filename='" & txtDelete.Text & "' ")
End If
Else
MsgBox("Por favor introduza um ficheiro a apagar!")
End If
RefreshDGV()
End Sub
And I've created a Sub method
Sub RefreshDGV()
Dim str1 As String = "SELECT * FROM infofile"
DataGridView1.DataSource = SQLDataSet.Tables(0)
End Sub
This is not working...
Try this:
Dim strSql As String = "SELECT * FROM infofile"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
cnn.Open()
Using dad As New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
End Using
cnn.Close()
DataGridView1.DataSource = dtb
End Using

Forgot Password Form Issues VB.net

I am trying to create a forgot password screen for my application. I am using the tab control for the different pages. My current code is able to create a user but it is able to create duplicates (Which is an issue needed to be rectified) I then have an issue with the forget password screen not working completely.
My code is:
Imports System.Data.OleDb
Public Class Form2
Dim connection As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim DBTest1 As String
Dim DBTestP1 As String
Dim cmd As New OleDbCommand(sql, connection)
Dim connStr As String
Dim usernamevalid As Integer
Dim passwordvalid As Integer
Public Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
If User.Text.Length < 4 Then
usernamevalid = 0
ElseIf User.Text.Length > 4 Then
usernamevalid = 1
End If
If Pass.Text.Length < 5 Then
passwordvalid = 0
ElseIf Pass.Text.Length > 5 Then
passwordvalid = 1
End If
If usernamevalid = 0 Then
MsgBox("Username Must Be At Least 5 Characters")
End If
If passwordvalid = 0 Then
MsgBox("Password Must Be At Least 5 Characters")
End If
If passwordvalid And usernamevalid = 1 And Pass.Text = RePass.Text Then
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Daniel\Documents\Robocopy.accdb"
Dim connStr = dbProvider & dbSource
DBTest1 = User.Text
DBTestP1 = Pass.Text
sql = "INSERT INTO Robocopy(username,[password],sq,sqa) VALUES('" & DBTest1 & "','" & DBTestP1 & "','" & SQREG.Text & "', '" & SQAREG.Text & "')"
Using connection = New OleDb.OleDbConnection(connStr)
Using cmd = New OleDb.OleDbCommand(sql, connection)
connection.Open()
cmd.ExecuteNonQuery()
connection.Close()
MsgBox("User Created!")
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Using
End Using
ElseIf Not Pass.Text = RePass.Text Then
MsgBox("Passwords did not match")
End If
End Sub
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim result = MessageBox.Show(" Are you sure you want to quit", "Are you sure?", MessageBoxButtons.YesNoCancel)
Me.Close()
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If NewPass.Text = ReNewPass.Text Then
Try
connection.Open()
cmd = New OleDbCommand("update robocopy set [password] = '" & NewPass.Text & "' where username = '" & UserFGT.Text & "'", connection)
cmd.ExecuteNonQuery()
MessageBox.Show("PASSWORD CHANGE SUCCESSFULLY")
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
End Class
The exception it catches is The ConnectionString property has not been initialized
Currently I changed my code to what I think you mean:
Button4's code has been changed as such:
Private Sub ResetPassword_Click(sender As Object, e As EventArgs) Handles ResetPassword.Click
If NewPass.Text = ReNewPass.Text Then
Using connection = New OleDb.OleDbConnection(connStr)
Using cmd = New OleDb.OleDbCommand(sql, connection)
connection.Open()
cmd = New OleDbCommand("update robocopy set [password] = '" & NewPass.Text & "' where username = '" & UserFGT.Text & "'", connection)
cmd.ExecuteNonQuery()
MessageBox.Show("PASSWORD CHANGE SUCCESSFULLY")
connection.Close()
End Using
End Using
End If
End Sub
I now get the error for cmd = New OleDbCommand("update robocopy set [password] = '" & NewPass.Text & "' where username = '" & UserFGT.Text & "'", connection)
I am getting the error for cmd where it says 'Read Only' Variable cannot be the target of assignment
The only thing I can see wrong with the connection string are extra spaces after 'Data Source='.
Here's an example from connectionstrings.com:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb;Persist Security Info=False;

VB 2010 express trouble after project build automating excel

I am automating excel through vb2010 express. The project is working fine, but when I publish it, it is only working when the actual spreadsheet is open on the computer. If it isn't open, the ExecuteNonQuery functions errors out with no connection open even though it is coded to open on form load. What am I missing?
Thank you in advance,
Here is part of my code...
Public Class frmTrustDeposit
Dim cn As New OleDbConnection
Dim cm As New OleDbCommand
Dim da As OleDbDataAdapter
Dim dt As New DataTable
Private Sub frmTrustDeposit_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Beosma\Documents\HFH\pnTrustDeposits2015.xlsx;Extended Properties=Excel 8.0;"
cn.Open()
FillDataGridView("select * from [Sheet1$]")
End Sub
Private Sub FillDataGridView(ByVal Query As String)
da = New OleDbDataAdapter(Query, cn)
dt.Clear()
da.Fill(dt)
With DataGridView1
.DataSource = dt
.Columns(0).HeaderText = "PreNeed"
.Columns(1).HeaderText = "Buyer"
.Columns(2).HeaderText = "Beneficiary"
.Columns(3).HeaderText = "Date"
.Columns(4).HeaderText = "Payment"
.Columns(5).HeaderText = "Retained"
.Columns(6).HeaderText = "Deposit"
.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
End Sub
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
Try
With cm
.Connection = cn
.CommandText = "insert into [Sheet1$]values('" & txtPreNeed.Text & "','" & txtBuyerName.Text & "', '" & txtBeneficiaryName.Text & "','" & txtDateReceived.Text & "', '" & txtPaymentAmount.Text & "', '" & txtRetainedAmount.Text & "', '" & txtDepositAmount.Text & "')"
.ExecuteNonQuery()
End With
FillDataGridView("select * from [Sheet1$]")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, Text)
Return
End Try
MsgBox("Successfully updated!", MsgBoxStyle.Information, Text)
Call ClearTextBoxes(Me)
End Sub
End Class
Banana, what happens is when the excel sheet is not open, the datagrid fails to populate on load and the ExecuteNonQuery gets the error. If the sheet is open and I run the program, there are no errors at all.

How to read and move read content via SQL into variables within VB.net and use a connectionstring from a module in forms?

This is my first question, by the way - and I'm not sure exactly how to ask, or say what's wrong. There's 3 things I can't sort so any help would be appreciated.
Module:
This and the first (login) form work as they are but I couldn't get either Form to reference con.connectionstring for them to use without having to re-use the string contained in "" (as they do below) - my attempts ended up with errors including saying that the state couldn't be changed as the connection was already open, but I'd like the same one string to be referenced from the Forms.
Module ConnectionModule
Public con As OleDb.OleDbConnection = New OleDb.OleDbConnection
Public da As OleDb.OleDbDataAdapter
Public ds As DataSet = New DataSet
Public Path As String = Application.StartupPath
Public Sub OpenDb()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
con.Open()
If con.State = ConnectionState.Closed Then
MsgBox("Connection to db not made.")
End If
End Sub
Public CurrentUser As String = Nothing
End Module
The First Form:
Public Class LoginForm
Private Sub LoginForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
OpenDb()
con.Close()
End Sub
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim ID As String = txtID.Text
Dim Pass As String = txtPassword.Text
If IsNumeric(ID) = False Or ID.Length > 4 Or Pass = Nothing Then
MsgBox("Staff ID is a 4-digit number and Password must not be blank.")
Else
Dim con As New System.Data.OleDb.OleDbConnection()
OpenDb()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Try
Dim sql As String = "SELECT * FROM tblStaff WHERE [StaffID]='" & ID & "' AND [Pword] = '" & Pass & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = con
con.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Read() Then 'Correct:
MenuForm.Show()
Me.Hide()
CurrentUser = ID
Else 'Incorrect:
MsgBox("Staff ID or Password incorrect.")
txtPassword.Text = ""
txtID.Text = ""
txtID.Focus()
End If
Catch ex As Exception
MsgBox("Database Connection Error.")
End Try
con.Close()
End If
End Sub
End Class
A form to change the password:
The problem here is that lblUser (A clarification for the user to tell them which password will be changed) only outputs the data already within the program as a variable: CurrentUser (as assigned upon successful login). No error is produced but the full name of the user isn't shown (or possibly read from the database).
I'm also unsure how the UPDATE SQL command should be contained within the second procedure, btnAccept_click, here. What the syntax is, basically. I haven't found a clear example to look at.
Imports System.Data.OleDb
Public Class PasswordForm
Private Sub PasswordForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con = New System.Data.OleDb.OleDbConnection()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Dim Returned(2) As String
CurrentUser = CurrentUser
Dim cmd As OleDbCommand = New OleDbCommand("SELECT [Title], [Forename], [Surname] FROM tblStaff WHERE [StaffID]='" & CurrentUser & "'", con)
Try
con.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
reader.Read()
'Makes db contents variables
Returned(0) = reader.Item("[Title]").ToString
Returned(1) = reader.Item("[Forename]").ToString
Returned(2) = reader.Item("[Surname]").ToString
End If
reader.Close()
Catch ex As Exception
Me.Hide()
MsgBox("Database Connection Error.")
Finally
con.Close()
End Try
lblUser.Text = "Current User: " & CurrentUser & Returned(0) & Returned(1) & Returned(2)
''Only outputs CurrentUser
End Sub
Private Sub btnAccept_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAccept.Click
Dim Current As String = txtCurrent.text
Dim NewPass As String = txtNew.Text
'Verification
If txtNew.Text = txtConfirm.Text And NewPass.Length <= 20 Then
Dim cmd As OleDbCommand = New OleDbCommand("UPDATE tblStaff SET [Pword]='" & NewPass & "' WHERE [StaffID]='" & CurrentUser & "'", con)
End If
End Sub
End Class
Thank you, again, for anyone with ideas (especially exact code).
Oh and throughout what's here there are no errors thrown. Just missing content.
you are opening the connection in openDB() and you are trying to open it again in form1, this will throw the error you are getting. So comment all the con related lines in your form. Same comment for your passowrd form also.
'Dim con As New System.Data.OleDb.OleDbConnection()
OpenDb()
'con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=F:\Computing A2\CG4 Coursework\Greener Cleaning\dbCoursework.accdb"
Try
Dim sql As String = "SELECT * FROM tblStaff WHERE [StaffID]='" & ID & "' AND [Pword] = '" & Pass & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = con
'con.Open()
...
end try

Visual Basic HowTo: Retrieve Data from .mdf

What am I doing wrong? I have been going at this for a while now... I surrender.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using sqlCon = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\gadgetDatabase.mdf;Integrated Security=True")
Dim Id As Integer = 2
'With the use of ID, it will get the appName or Application Display Name
sqlCon.Open()
Dim sqlText = "SELECT appName " & _
"FROM appTable " & _
"WHERE Id = #sqlID"
Dim sqlCmd = New SqlCommand(sqlText, sqlCon)
sqlCmd.Parameters.AddWithValue("#sqlID", Id)
'sqlCmd.ToString()
sqlCmd.ExecuteScalar() 'I had these in there before I copied the code over
sqlCon.Close()
Label3.Text = sqlText 'For testing or confirmation it went correctly...
End Using
End Sub
You forgot to call
string apName = sqlCmd.ExecuteScaler();
and retrieve the result.
If a resultset (multiple results) is expected, then call reader = cmd.ExecuteReader() and loop through the results.