Update an Excel worksheet using VB.net - vb.net

I am able to insert and read data of an Excel file but unable to update the data using article_no as trigger,
I have tried this
Dim cn As New OleDbConnection
Dim cm As New OleDbCommand
cn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\crys\Desktop\TEST\Book1.xls;Extended Properties=""Excel 12.0 Xml;HDR=YES""")
cn.Open()
With cm
.Connection = cn
.CommandText = "UPDATE [up$] SET name = '" & TextBox2.Text & "', QC_status ='" & ComboBox1.SelectedItem & "', reason='" & TextBox3.Text & "', date='" & DateTimePicker1.Text & "' WHERE article_no = '" & TextBox1.Text & "'"
If (ExecuteQuery(.CommandText) = True) Then
MsgBox("record updated")
End If
End With
cn.Close()
But it is showing me an error invalid object 'up$'.
Please someone help me fix this problem.

finally got my query right for updating excel sheet, code goes like this :
Dim cn As New OleDbConnection
Dim cm As New OleDbCommand
cn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\crysol\Desktop\TEST\Book1.xls;Extended Properties=""Excel 12.0 Xml;HDR=YES""")
cn.Open()
With cm
.Connection = cn
.CommandText = "update [up$] set [name]=?, [QC_status]=?, [reason]=?, [date]=? WHERE [article_no]=?"
cm = New OleDbCommand(.CommandText, cn)
cm.Parameters.AddWithValue("?", TextBox2.Text)
cm.Parameters.AddWithValue("?", ComboBox1.SelectedItem)
cm.Parameters.AddWithValue("?", TextBox3.Text)
cm.Parameters.AddWithValue("?", DateTimePicker1.Text)
cm.Parameters.AddWithValue("?", TextBox1.Text)
cm.ExecuteNonQuery()
MsgBox("UPDATE SUCCESSFUL")
con.Close()
End With

Generally , it is how its done. I am not able to find any error in your code:
Imports System.Data
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim myCommand As New System.Data.OleDb.OleDbCommand
Dim sql As String
MyConnection = New System.Data.OleDb.OleDbConnection _
("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + _
"'c:\testfile.xls';Extended Properties=Excel 8.0;")
MyConnection.Open()
myCommand.Connection = MyConnection
sql = "Update [Sheet1$] set name = 'New Name' where id=1"
myCommand.CommandText = sql
myCommand.ExecuteNonQuery()
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
MsgBox("Updated ")
End Sub
End Class
Hope this helps..

Related

data type mismatch criteria expression in vb.net,access while inserting

Imports System.Data.OleDb
Imports System.IO
Public Class insuranceform
Dim read As String
Dim datafile As String
Dim connstring As String
Dim cmd As New OleDbCommand
Public da As New OleDbDataAdapter
Dim str As String
Public ds As New DataSet
Public ds1 As New DataSet
Public ds2 As New DataSet
Dim myconnection As OleDbConnection = New OleDbConnection
Dim er As Integer
Private Sub insuranceform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
read = "provider=microsoft.ace.oledb.12.0;data source="
datafile = "C:\Users\DELL\source\repos\HRIS SYSTEM\loginformdatabase\BLUESTREAM.accdb"
connstring = read & datafile
myconnection.ConnectionString = connstring
ds.Clear()
DateTimePicker1.Value = DateTime.Now
DateTimePicker2.Value = DateTime.Now
DateTimePicker3.Value = DateTime.Now
If myconnection.State = ConnectionState.Open Then
myconnection.Close()
End If
myconnection.Open()
er = 0
'cn.Open()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
End Sub
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Button1.Click
ds.Clear()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
If er = 0 Then
Try
cmd.Connection = myconnection
cmd.CommandText = "insert into insurancedetail(Name,EmployeeID,PAN,UniversalAccountNumber,AdharNo,CurrentAddress,PermanentAddress,Landline,MartialStatus,MobileNumber,EmergencyContactNo,BloodGroup,DoyouHaveHDFCbankaccount,NameOfdependentmember_F) values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & TextBox7.Text & "','" & TextBox8.Text & "','" & ComboBox2.Text & "','" & TextBox9.Text & "','" & TextBox10.Text & "','" & TextBox11.Text & "','" & ComboBox1.Text & "','" & TextBox12.Text & "')"
cmd.ExecuteNonQuery() 'if command is executed'
Dim result As Integer = MessageBox.Show("New insurance detail Added. Want To Add Another One.", "Added", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Close()
ElseIf result = DialogResult.Yes Then
ds.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
TextBox11.Clear()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
TextBox17.Clear()
TextBox18.Clear()
TextBox20.Clear()
ComboBox1.ResetText()
ComboBox2.ResetText()
ComboBox3.ResetText()
ComboBox4.ResetText()
ComboBox5.ResetText()
DateTimePicker1.ResetText()
DateTimePicker2.ResetText()
DateTimePicker3.ResetText()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
'insert close
End If
'myconnection close
End Sub
Way too many Class level variables. Especially not myconnection and cmd. What in the world is er? Procedures should not do too much. Move some code off to other procedures, especially if they will be called more than once.
For database objects use Using blocks. They will ensure that your objects are closed and disposed even if there is an error. You don't appear to be using the DataAdapter so just fill a DataTable directly. It can be bound to a DataGridView.
There is no reason to fill the DataTable again before the save. You may want to refill is again after the save.
I am guessing at the datatypes in your database. You must check the database to get the correct datatypes and for string types get the size of the field. Convert your TextBox values to the correct types. I have only used a few of your fields for demonstration purposes. Make sure you add your parameters in the same order that they appear in the sql statement.
Private dt As New DataTable
Private connString As String = "provider=microsoft.ace.oledb.12.0;data source=C:\Users\DELL\source\repos\HRIS SYSTEM\loginformdatabase\BLUESTREAM.accdb"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SetDatePickerValues()
FillDataTable()
End Sub
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Using cn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Insert Into insurancedetail(Name,EmployeeID,PAN) Values(#Name, #EmployeeID, #PAN);", cn)
cmd.Parameters.Add("#Name", OleDbType.VarChar, 100).Value = TextBox1.Text
cmd.Parameters.Add("#EmployeeID", OleDbType.Integer).Value = CInt(TextBox2.Text)
cmd.Parameters.Add("#PAN", OleDbType.VarChar, 100).Value = TextBox3.Text
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
FillDataTable()
Dim result As Integer = MessageBox.Show("New insurance detail Added. Want To Add Another One.", "Added", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Close()
Else
ClearForm()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ClearForm()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
TextBox11.Clear()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
TextBox17.Clear()
TextBox18.Clear()
TextBox20.Clear()
ComboBox1.ResetText()
ComboBox2.ResetText()
ComboBox3.ResetText()
ComboBox4.ResetText()
ComboBox5.ResetText()
SetDatePickerValues()
End Sub
Private Sub FillDataTable()
Try
dt.Clear()
Using cn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Select * From insurancedetail", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub SetDatePickerValues()
DateTimePicker1.Value = DateTime.Now
DateTimePicker2.Value = DateTime.Now
DateTimePicker3.Value = DateTime.Now
End Sub

How To Creating a new DataSet With ADO.net in VB.Net?

I am transferring data from the Excel file to the DataGridView. Then I transfer the data from the DataGridView to the table in SQL. Is there any other way I can do instead of manually entering column indices?
Are there any nonsense things you see in this code?
How to follow a path?
My teacher said search for using type dataset.
I did not find anything.
Public Class Form1
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private DBCon As New SqlConnection("Server=LENOVO-PC;Database=Customer;User ID=sa;Password=zeynep")
Private DBCmd As New SqlCommand
Public DBDA As SqlDataAdapter
Public DBDT As DataTable
Public Sub New(ConnectionString As String)
DBCon = New SqlConnection(ConnectionString)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim dataSet As System.Data.DataSet
Dim dataSet2 As System.Data.DataSet
Dim dataSet3 As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim MyCommand2 As System.Data.OleDb.OleDbDataAdapter
Dim MyCommand3 As System.Data.OleDb.OleDbDataAdapter
Dim path As String = "C:\\Users\\irem\\Desktop\\Customer.xls"
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0; HDR=YES;IMEX=1;';")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
dataSet = New System.Data.DataSet
MyCommand.Fill(dataSet)
DataGridView1.DataSource = dataSet.Tables(0)
MyCommand2 = New System.Data.OleDb.OleDbDataAdapter("select * from [41-GLN$]", MyConnection)
dataSet2 = New System.Data.DataSet
MyCommand2.Fill(dataSet2)
DataGridView2.DataSource = dataSet2.Tables(0)
MyCommand3 = New System.Data.OleDb.OleDbDataAdapter("select * from [Info$]", MyConnection)
dataSet3 = New System.Data.DataSet
MyCommand3.Fill(dataSet3)
DataGridView3.DataSource = dataSet3.Tables(0)
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
DBCon.Open()
DBCmd.Connection = DBCon
Dim i As Integer
For i = 0 To DataGridView1.Rows.Count - 1 Step +1
DBCmd.CommandText = "INSERT INTO Musteri(partner_id, type, fs_type, fullname, shortname, city, postalcode, address, tel, fax) VALUES('" & DataGridView1.Rows(i).Cells(0).Value & "','" & DataGridView1.Rows(i).Cells(1).Value & "','" & DataGridView1.Rows(i).Cells(2).Value & "','" & DataGridView1.Rows(i).Cells(3).Value & "','" & DataGridView1.Rows(i).Cells(4).Value & "','" & DataGridView1.Rows(i).Cells(5).Value & "','" & DataGridView1.Rows(i).Cells(6).Value & "','" & DataGridView1.Rows(i).Cells(7).Value & "','" & DataGridView1.Rows(i).Cells(8).Value & "','" & DataGridView1.Rows(i).Cells(9).Value & "')"
DBCmd.ExecuteNonQuery()
Next
For i = 0 To DataGridView2.Rows.Count - 1 Step +1
DBCmd.CommandText = "INSERT INTO GLN(GLN,partner_id) VALUES('" & DataGridView2.Rows(i).Cells(0).Value & "','" & DataGridView2.Rows(i).Cells(1).Value & "')"
DBCmd.ExecuteNonQuery()
Next
For i = 0 To DataGridView3.Rows.Count - 1 Step +1
DBCmd.CommandText = "INSERT INTO Info(Customer_Mast_Data) VALUES('" & DataGridView3.Rows(i).Cells(0).Value & "')"
DBCmd.ExecuteNonQuery()
Next
DBCon.Close()
MsgBox("Transfer is succesfully!")
End Sub
End Class

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;

Data from combobox to be viewed on datagridview

Dim cnn As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
Private Sub loadData()
If Not cnn.State = ConnectionState.Open Then
cnn.ConnectionString = "Provider=Microsoft.ACE.Oledb.12.0; Data Source=" & Application.StartupPath & "\LibrarySystem.accdb"
'open connection
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT StatusID, StatusDesc FROM BookStatus", cnn)
Dim dt As New DataTable
'fill data to datatable
da.Fill(dt)
'show data in data table into combobox
Me.cmbBookStatus.DataSource = dt
Me.cmbBookStatus.DisplayMember = "StatusDesc"
Me.cmbBookStatus.ValueMember = "StatusID"
'close connection
cnn.Close()
End Sub
I want to show the data from the combobox on datagridview. Above are the codes I used. I've made a table in microsoft access for the bookstatus. But the data still didn't show up at the combobox. Can someone help meeee.
I put the codes for viewing the combobox data on datagridview under the save button.
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim cnn As New OleDb.OleDbConnection
If Not cnn.State = ConnectionState.Open Then
cnn.ConnectionString = "Provider=Microsoft.ACE.Oledb.12.0; Data Source=" & Application.StartupPath & "\LibrarySystem.accdb"
cnn.Open()
End If
If (txtBookID.Text = "" And txtBookTitle.Text = "" And txtPub.Text = "" And txtAuthor.Text = "" And cmbBookStatus.SelectedValue = "") Then
MessageBox.Show("Please insert all field!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Dim msgbox As DialogResult = MessageBox.Show("Are you sure to save this record?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If msgbox = Windows.Forms.DialogResult.Yes Then
'add new data
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO Book(BookID, Title, Publisher, Author, StatusID) " & _
" VALUES('" & txtBookID.Text & "','" & txtBookTitle.Text & "','" & txtPub.Text & "','" & txtAuthor.Text & "','" & cmbBookStatus.SelectedValue & "')"
cmd.ExecuteNonQuery()
MessageBox.Show("Data has been recorded", "Add New Record", MessageBoxButtons.OK, MessageBoxIcon.Information)
txtBookID.Clear()
txtBookTitle.Clear()
txtPub.Clear()
txtAuthor.Clear()
End If
'refresh data
'Me.loadData()
Dim db As New OleDb.OleDbDataAdapter("SELECT * FROM Book", cnn)
Dim dt As New DataTable
'fill data to datatable
db.Fill(dt)
'show data in data table into datagridview
Me.dgvAddBook.DataSource = dt
Dim column As DataGridViewColumn = dgvAddBook.Columns(1)
column.Width = 269
End If
'close connection
cnn.Close()
End Sub

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.