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.
Related
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
I'm trying to refresh the DataGridView right after executing an SQL Command, so when the user presses the update button all details must change as well as the DataGridView. This is my code and I don't know where to add this function.
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click, Button5.Click
Try
Dim a As String
cn.Open()
Dim cmd As New System.Data.SqlClient.SqlCommand
cmd = New SqlCommand("update Addemployees set Fname= '" & TextBox1.Text & "', Lname= '" & TextBox3.Text & "', ID= '" & TextBox4.Text & "', CIN= '" & TextBox2.Text & "', phone= '" & TextBox6.Text & "', Email= '" & TextBox5.Text & "', fromD= '" & TextBox8.Text & "', toD= '" & TextBox7.Text & "' where ID='" & ComboBox1.Text & "' ", cn)
cmd.Connection = cn
a = cmd.ExecuteNonQuery()
MessageBox.Show("Process successful!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information)
cn.Close()
Catch
MessageBox.Show("Error!", "exit", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
cn.Dispose()
End Try
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
DateTimePicker2 = Nothing
DateTimePicker1 = Nothing
End Sub
You can just create a Method or a Function that displays data in the DATAGRIDVIEW and then call the method whenever you add/delete/update just be sure to add/delete/update first before calling the method or function
Sub display()
Dim temp As Double = 0
Dim lt As String = "select id as ID, vlname as Last, vfname as First,
vmname as Middle, vgnd as Gender, vdob as Birthday, iage as
Age, vcourse as Course from tbreg where vlname Like '" +
tbsearch.Text + "%' or vfname Like '" + tbsearch.Text + "%'
order by vlname asc"
Dim da As New MySqlDataAdapter(lt, con)
con.Open()
Dim ds As New DataSet
da.Fill(ds, "tbreg")
da.Dispose()
dgv.DataSource = ds.Tables(0)
con.Close()
End Sub
Just add the display() method right after saving/deleting/updating your database
'updating and then refreshing the datagridview right after doing the update you
just have to call the method
Dim supdate As String = "Update tbuser set vname = '" & tbname.Text & "',
vemail = '" & tbemail.Text & "', vuser = '" &
tbuser.Text & "', vpass = '" & tbpass.Text & "' where
vid = '" & dgv.SelectedCells(0).Value & "'"
Dim cmd As New MySqlCommand(supdate, con)
con.Open()
cmd.ExecuteNonQuery()
MsgBox("Successfully Updated!!!", MsgBoxStyle.Information,
"System COnfirmed!")
con.Close()
'display method here!
display()
You can do one thing here. After the save is successful, call the procedure you used to view the contents in DataGridView This works.
I will show you my example:
I have a student attendance adding/viewing form. There is a TabControl with two tabs, one for adding and another for viewing.
In the add tab, there is a button which submits the attendance of students to a database. After the submission is done, I then show a message like this:
Private Sub SubmitBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SubmitBtn.Click
'{rest of the code}
'add attendance success
MsgBox("Attendance added for " & yyyy_txt.Text & "/" & mm_txt.Text & "/" & dd_txt.Text, MsgBoxStyle.Information)
End Sub
In the view tab, there are few option on how the user wants to see the attendance record which is done by selecting option from ComboBoxes and then clicking the SearchBtn button.
'search attendance
Private Sub SearchBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchBtn.Click
If SelectClass2.Text = "" Or SearchType.Text = "" Or SearchKey.Text = "" Then
MsgBox("Select search options to continue", MsgBoxStyle.Critical)
Else
If SearchType.Text = "By Date" Then
'search by date, call procedure 'displayatt'
Dim xyz As String = SearchKey.Text.Substring(0, 5)
displayatt(SearchKey.Text, SelectClass2.Text, String.Format("YYYY/MM/DD", xyz), True)
Else
'search by student, call procedure 'displayatt'
displayatt(SearchKey.Text.Substring(3, SearchType.Text.Length - 3), SelectClass2.Text, SearchKey.Text.Substring(0, 5), False)
End If
End If
End Sub
Well, you can update the DataGridView1 contents by calling the procedure which shows the contents. In my case, I would add SearchBtn_Click(SearchBtn, Nothing) right after showing the messagebox about the completion of adding the attendance. Then it will look like this:
Private Sub SubmitBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SubmitBtn.Click
'{rest of the code}
'add attendance success
MsgBox("Attendance added for " & yyyy_txt.Text & "/" & mm_txt.Text & "/" & dd_txt.Text, MsgBoxStyle.Information)
SearchBtn_Click(SearchBtn, Nothing)
End Sub
Try it. :)
Use this class for Microsoft SQL and see the LoadDB for how to use it. Also don't hardcode you query like you did. Someone using your app could do SQL injection and drop your tables. Use params like I showed you. You probably also want to update only a specific record so add the WHERE instruction in your query
Sub LoadDB
dim xdb as new dbMSSQL
dim SQLQuery as String = "update Addemployees set fname=#colfname, lname=#collanme, etc WEHRE ID=#colID"
xdb.addparam("#colid",RecordID)
xdb.addparam("#colfname",textbox1.text)
xdb.addparam("#collname",textbox2.text)
.......
xdb.execquery(Sqlquery)
datagridview1.datasource=xdb.dbdt
end sub
Imports System.Data.SqlClient
Public Class dbMSSQL
' CREATE YOUR DB CONNECTION
Public SQLSource As String = "Data Source=[yourcomputer]\sqlexpress;Integrated Security=True"
Private DBCon As New SqlConnection(SQLSource)
'Private DBCon As New MySqlConnection(SQLSource)
' PREPARE DB COMMAND
Private DBCmd As SqlCommand
' DB DATA
Public DBDA As SqlDataAdapter
Public DBDT As DataTable
' QUERY PARAMETERS
Public Params As New List(Of SqlParameter)
' QUERY STATISTICS
Public RecordCount As Integer
Public Exception As String
Public Sub ExecQuery(Query As String)
' RESET QUERY STATS
RecordCount = 0
Exception = ""
Try
' OPEN A CONNECTION
DBCon.Open()
' CREATE DB COMMAND
DBCmd = New SqlCommand(Query, DBCon)
' LOAD PARAMS INTO DB COMMAND
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
' CLEAR PARAMS LIST
Params.Clear()
' EXECUTE COMMAND & FILL DATATABLE
DBDT = New DataTable
DBDA = New SqlDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DBDT)
Catch ex As Exception
Exception = ex.Message
End Try
' CLOSE YOUR CONNECTION
If DBCon.State = ConnectionState.Open Then DBCon.Close()
End Sub
' INCLUDE QUERY & COMMAND PARAMETERS
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New SqlParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
here actual code from a project
Dim xDB As New mysql
xDB.AddParam("#colisconnected", 1)
xDB.AddParam("#colcpuid", CPUid)
xDB.AddParam("#colfwuid", userId)
xDB.ExecQuery("UPDATE clients.computerinfo SET isconnected=#colisconnected WHERE (cpuid=#colcpuid) and (customerid=#colfwuid)")
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
is there anything wrong with my code?
i want to add, update and delete in a database using vb13
here is my code
Public Class Form1
Dim cnn As New OleDb.OleDbConnection
Private Sub cmdexit_Click(sender As Object, e As EventArgs) Handles cmdexit.Click
Close()
End Sub
Private Sub cmdclear_Click(sender As Object, e As EventArgs) Handles cmdclear.Click
txtaddress.Text = ""
txtstdntid.Text = ""
txtstdntname.Text = ""
txttelephone.Text = ""
txtstdntid.Tag = ""
cmdedit.Enabled = True
cmdadd.Text = "Add"
txtstdntid.Focus()
End Sub
Private Sub RefreshData()
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT stdid as [ID], " & "stdname as [Name], Gender, Phone, Address " & "FROM student ORDER BY stdid", cnn)
Dim dt As New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
cnn.Close()
End Sub
Private Sub cmdadd_Click(sender As Object, e As EventArgs) Handles cmdadd.Click
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
If txtstdntid.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO Student(stdid, stdname, gender, phone, address) " & "VALUES(" & txtstdntid.Text & ",'" & txtstdntname.Text & "','" & Cmbgender.Text & "','" & txttelephone.Text & "','" & txtaddress.Text & "')"
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE student" & "SET stdid=" & txtstdntid.Text & ", stdname='" & txtstdntname.Text & "'" & ", gender='" & Cmbgender.Text & "'" & ", phone='" & txttelephone.Text & "'" & "WHERE stdid=" & txtstdntid.Tag
cmd.ExecuteNonQuery()
End If
RefreshData()
cmdclear.PerformClick()
cnn.Close()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cnn = New OleDb.OleDbConnection
cnn.ConnectionString = "Provider=Mircosoft.Jet.Oledb.4.0; Data Source=" & Application.StartupPath & "\data.mdb"
RefreshData()
End Sub
Private Sub cmdedit_Click(sender As Object, e As EventArgs) Handles cmdedit.Click
If DataGridView1.Rows.Count > 0 Then
If DataGridView1.SelectedRows.Count > 0 Then
Dim intStdID As Integer = DataGridView1.SelectedRows(0).Cells("id").Value
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM student " & "WHERE stdid=" & intStdID, cnn)
Dim dt As New DataTable
da.Fill(dt)
txtstdntid.Text = intStdID
txtstdntname.Text = dt.Rows(0).Item("stdname")
Cmbgender.Text = dt.Rows(0).Item("gender")
txttelephone.Text = dt.Rows(0).Item("phone")
txtaddress.Text = dt.Rows(0).Item("address")
txtstdntid.Tag = intStdID
cmdadd.Text = "Update"
cmdedit.Enabled = False
cnn.Close()
End If
End If
End Sub
Private Sub cmddelete_Click(sender As Object, e As EventArgs) Handles cmddelete.Click
If DataGridView1.Rows.Count > 0 Then
If DataGridView1.SelectedRows.Count > 0 Then
Dim intStdID As Integer = DataGridView1.SelectedRows(0).Cells("id").Value
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = cnn
cmd.CommandText = "DELETE FROM student WHERE stdid=" & intStdID
cmd.ExecuteNonQuery()
RefreshData()
cnn.Close()
End If
End If
End Sub
End Class
That error is usually a result of your app running in a 64-bit process while the Jet OLE DB provider only exists as a 32-bit library. If you want to use Jet on a 64-bit machine then you must ensure that your app runs in a 32-bit process. You do that by setting the Target Platform in the project properties to x86 or, if available, leave it set to the default Any CPU and check the Prefer 32-bit box. Your app will then run in a 32-bit process on all machines, whether the OS is 32-bit or 64-bit.
i got 2 forms... Dress_Price is for displaying the data form database ( MS Access 2007 ) another form,Edit_Dress is to edit and update the database..
the code successfully updated the data based on the changes from the form Edit_Dress.. but there is 2 problems -
the dgvCustomerDressPrice did not refreshed after updating..
there is "space" being added to the record after updated..
before update price value
Dress_Name = "Tuxedo" Dress_Price = "150"
after update price value
Dress_Name = " Tuxedo" Dress_Price = " 250"
the "space" keeps being added up everytime i update the record... so the search function cant work properly because of the space..
code on Dress_Price :-
Private Sub Dress_Price_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\annonymous\Documents\Visual Studio 2012\Projects\TMS Final\TMS Final\db\db_TMS.accdb"
con.Open()
dgvCustomerDressPrice()
End Sub
Private Sub dgvCustomerDressPrice()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New OleDb.OleDbDataAdapter
da = New OleDb.OleDbDataAdapter("SELECT * FROM tbl_dress", con)
da.Fill(dt)
dgvDressPrice.DataSource = dt.DefaultView
dgvDressPrice.SelectionMode = DataGridViewSelectionMode.FullRowSelect
con.Close()
End Sub
Private Sub btnEditDress_Click(sender As Object, e As EventArgs) Handles btnEditDress.Click
If dgvDressPrice.Rows.Count > 0 Then ' when user click a row, any query for database will based on Order_ID
If dgvDressPrice.SelectedRows.Count > 0 Then
Dim intDressID As Integer = dgvDressPrice.SelectedRows(0).Cells("Dress_ID").Value
Try
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM tbl_dress WHERE Dress_ID =" & intDressID, con)
' the record that will be edited is based on the Customer_ID of particular row clicked
Dim dt As New DataTable
da.Fill(dt)
Edit_Dress.txtDressID.Text = intDressID
Edit_Dress.txtDressName.Text = dt.Rows(0).Item("Dress_Name")
Edit_Dress.txtDressPrice.Text = dt.Rows(0).Item("Dress_Price")
' pass the data from tbl_user into each represented field
Catch ex As Exception
MessageBox.Show("Failed to edit data ! System eror : " & ex.ToString, "Eror !", MessageBoxButtons.OK)
End Try
End If
End If
Edit_Dress.Show()
End Sub
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM tbl_dress WHERE Dress_Name like '" & txtSearch.Text & "%' ", con)
Dim dt As New DataTable
da.Fill(dt)
dgvCustomerDressPrice().DataSource = dt
con.Close()
End Sub
code on Edit_Dress :-
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
con = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\annonymous\Documents\Visual Studio 2012\Projects\TMS Final\TMS Final\db\db_TMS.accdb")
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim intDressID As Integer
intDressID = Convert.ToInt32(txtDressID.Text)
intDressID = Integer.Parse(txtDressID.Text)
Dim intDressPrice As Integer
intDressPrice = Convert.ToInt32(txtDressPrice.Text)
intDressPrice = Integer.Parse(txtDressPrice.Text)
Dim query As String = "UPDATE tbl_dress SET Dress_Name = ' " & txtDressName.Text & " ' , Dress_Price = ' " & intDressPrice & " ' WHERE Dress_ID = " & intDressID & " "
Dim cmd As New OleDb.OleDbCommand(query, con)
cmd.ExecuteNonQuery()
MessageBox.Show("Data updated !", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
Dress_Price.RefreshPriceList()
con.Close()
Me.Close()
Catch ex As Exception
MessageBox.Show("Failed to save into database ! System eror : " & ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Looking at your UPDATE method it is clear why you have a space added every time. You put it in the update string.
Dim query As String = "UPDATE tbl_dress SET Dress_Name = ' " & _
^ here
txtDressName.Text & " ' , Dress_Price = ' " & _
^here ^here
intDressPrice & " ' WHERE Dress_ID = " & intDressID & " "
^here
A part from the simple error that could be fixed removing the space, this is not the correct way to create an update command. You should use a parameterized query
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
con = New OleDb.OleDbConnection(.....)
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim intDressID As Integer
intDressID = Convert.ToInt32(txtDressID.Text)
Dim intDressPrice As Integer
intDressPrice = Convert.ToInt32(txtDressPrice.Text)
Dim query As String = "UPDATE tbl_dress SET Dress_Name = ?, Dress_Price = ? " & _
"WHERE Dress_ID = ?"
Dim cmd As New OleDb.OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#p1", txtDressName.Text)
cmd.Parameters.AddWithValue("#p2", intDressPrice)
cmd.Parameters.AddWithValue("#p3", intDressID)
cmd.ExecuteNonQuery()
.....