Database not Updating 1000 - sql

Hi heres the code it has no errors but when you check the database nothing is added
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Create_btn.Click
Call getConnect()
If New_Username.Text = "" And New_Password.Text = "" And New_Pass_Code.Text = "" Then
MsgBox("check the empty textbox or wrong Admin Password", MsgBoxStyle.Critical, "needed")
Else
con.Open()
sql = "INSERT into Accounts (Username, Password, Pass_Code) values('" _
& New_Username.Text & "','" _
& New_Password.Text & "' , '" _
& New_Pass_Code.Text & "')"
Dim sqlcomd As New SqlClient.SqlCommand
sqlcomd.CommandText = sql
sqlcomd.Connection = con
sql = sqlcomd.ExecuteNonQuery
MsgBox("data saved")
con.Close()
End If

try to check your connection string. the data might be saving to another database.

Related

vb.net how to create the login permission

Private Sub Edit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Edit.Click
LoginForm.ShowDialog()
If Me.DataGridView1.Rows.Count > 0 Then
If Me.DataGridView1.SelectedRows.Count > 0 Then
Dim intcid1 As Integer = Me.DataGridView1.SelectedRows(0).Cells("ID").Value
'open connection
If Not cn3.State = ConnectionState.Open Then
cn3.Open()
End If
'get data into datatable
Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM stock " & _
" WHERE cid=" & intcid1, cn3)
Dim dt As New DataTable
da.Fill(dt)
Me.txtbarcode.Text = intcid1
Me.txtdetail1.Text = dt.Rows(0).Item("CheckerDetail")
Me.txtbarcode.Tag = intcid1
'change button save to update
Me.save.Text = "Update"
'disable button edit
'Me.Edit.Enabled = True
Me.save.Enabled = True
End If
End If
cn3.Close()
End Sub
Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
Dim cmd As New OleDb.OleDbCommand
If Not cn3.State = ConnectionState.Open Then
'open connection if it is not open yet
cn3.Open()
End If
cmd.Connection = cn3
cmd.CommandText = "INSERT INTO stock([checkercid],[CheckerName],[ShipQuantity],[Date],[CompanyName],[CheckerDetail]) " &
"VALUES( '" & getLastNumber().ToString & "','" & Me.txtCN.Text & "', '" & Me.txtQty.Text & "', '" & Date.Now.ToString("yyyy-MM-dd HH:mm:ss") & "', '" & Me.txtCompanyN.Text & "', '" & Me.txtdetail1.Text & "')"
'Error message if user not fill yhe textbox
If txtdetail1.Text.Trim = "" Then
MessageBox.Show("Please Insert Data", "Error Message")
Exit Sub
End If
cmd.CommandText = "UPDATE stock " & _
" SET" & _
" [CheckerDetail]='" & Me.txtdetail1.Text & "'" & _
" WHERE [cid]=" & DataGridView1("ID", DataGridView1.CurrentCell.RowIndex).Value
MsgBox("Update Data Successful", MsgBoxStyle.OkOnly, "Message")
cmd.ExecuteNonQuery()
Me.btnClear.PerformClick()
RefreshData1()
cn3.Close()
End Sub
I moved things around trying to keep the User Interface code in the Form and the Data Access code in your class. You had Retries in 2 different places. You only need it in one. boolresetPassword is never used in your code. Since you are hard coding the password don't set a bunch of properties of the class in the form. Just put your connection string in the constructor of the connection in the class. The validated data for the LogIn function is passed to the function.
You don't need all those properties in your class. Just add your connection string. You can pass your Select statement and the connection directly to the constructor of the command. Don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
I changed the Select to retrieve Count which is all you need to know.
As far as the Cancel button ask a new question with the code for the cancel button.
Public Class LoginForm
Private Retrys As Integer 'Integers automatically initialize to zero
Private Sub Ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ok.Click
If Retrys = 2 Then
MessageBox.Show("Sorry, you have exceeded the maximum number of attempts to login")
Close()
End If
Dim AppLogin As New ApplicatioLogin
'Do your validation here; not in the Data Access code.
If Not String.IsNullOrWhiteSpace(un.Text) AndAlso Not String.IsNullOrWhiteSpace(pw.Text) Then
If AppLogin.Login(un.Text, pw.Text) Then
SensitiveDataForm.Load()
Close()
Else
Retrys += 1
MessageBox.Show("Login Failed")
End If
Else
MessageBox.Show("Please fill in both username and password")
End If
End Sub
End Class
Public Class ApplicatioLogin
Public Function Login(UserName As String, UserPassword As String) As Boolean
Dim recordCount As Integer
Using cn As New OleDb.OleDbConnection("Your connection string")
Using cmd As New OleDb.OleDbCommand("SELECT Count(*) FROM Users
WHERE UserName = #UserName AND UserPassword = #UserPassword", cn)
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = UserName
cmd.Parameters.Add("#UserPassword", OleDbType.VarChar).Value = UserPassword
cn.Open()
recordCount = CInt(cmd.ExecuteScalar)
End Using
End Using
If recordCount = 1 Then
Return True
Else
Return False
End If
End Function
End Class

How to instantly refresh DataGridView after executing SQL Command

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)")

cmd.ExecuteNonQuery() no value given for one or more required parameters

I can't add any data but there is no error in my codes it always appear no value given for one or more required parameters. can someone help me this is my project.........................................
Public Class frmStudent
Dim cnn As New OleDb.OleDbConnection
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
Me.txtstdID.Text = ""
Me.txtStdName.Text = ""
Me.txtPhone.Text = ""
Me.txtAddress.Text = ""
Me.txtstdID.Tag = ""
'enable button edit
Me.btnEdit.Enabled = True
'set button add to add label
Me.btnAdd.Text = "Add"
'
Me.txtstdID.Focus()
End Sub
Private Sub RefreshData()
If Not cnn.State = ConnectionState.Open Then
'open connection
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
'fill data to datatable
da.Fill(dt)
'offer data in data table into datagridview
Me.dgvData.DataSource = dt
'close connection
cnn.Close()
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
'open connection if it is not yet open
cnn.Open()
End If
cmd.Connection = cnn
'check whether add new or update
If Me.txtstdID.Tag & "" = "" Then
'add new
'add data to table
cmd.CommandText = "INSERT INTO student(stdid, stdname, gender, phone, address) " & _
" VALUES(" & Me.txtstdID.Text & ",'" & Me.txtStdName.Text & "','" & _
Me.cboGender.Text & "','" & Me.txtPhone.Text & "','" & _
Me.txtAddress.Text & "')"
cmd.ExecuteNonQuery()
Else
'update data in table
cmd.CommandText = "UPDATE student " & _
" SET stdid=" & Me.txtstdID.Text & _
", stdname='" & Me.txtStdName.Text & "'" & _
", gender='" & Me.cboGender.Text & "'" & _
", phone='" & Me.txtPhone.Text & "'" & _
", address='" & Me.txtAddress.Text & "'" & _
" WHERE stdid=" & Me.txtstdID.Tag
cmd.ExecuteNonQuery()
End If
'refresh data in list
RefreshData()
'clear form
Me.btnClear.PerformClick()
'close connection
cnn.Close()
End Sub
Private Sub frmStudent_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
cnn = New OleDb.OleDbConnection
cnn.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & Application.StartupPath & "\data.mdb"
'
'get data into list
Me.RefreshData()
End Sub
Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
'check for the selected item in list
If Me.dgvData.Rows.Count > 0 Then
If Me.dgvData.SelectedRows.Count > 0 Then
Dim intStdID As Integer = Me.dgvData.SelectedRows(0).Cells("id").Value
'get data from database followed by student id
'open connection
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
'get data into datatable
Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM student " & _
" WHERE stdid=" & intStdID, cnn)
Dim dt As New DataTable
da.Fill(dt)
Me.txtstdID.Text = intStdID
Me.txtStdName.Text = dt.Rows(0).Item("stdname")
Me.cboGender.Text = dt.Rows(0).Item("gender")
Me.txtPhone.Text = dt.Rows(0).Item("phone")
Me.txtAddress.Text = dt.Rows(0).Item("address")
'
'hide the id to be edited in TAG of txtstdid in case id is changed
Me.txtstdID.Tag = intStdID
'change button add to update
Me.btnAdd.Text = "Update"
'disable button edit
Me.btnEdit.Enabled = False
'close connection
cnn.Close()
End If
End If
End Sub
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
'check for the selected item in list
If Me.dgvData.Rows.Count > 0 Then
If Me.dgvData.SelectedRows.Count > 0 Then
Dim intStdID As Integer = Me.dgvData.SelectedRows(0).Cells("id").Value
'open connection
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
'delete data
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = cnn
cmd.CommandText = "DELETE FROM student WHERE stdid=" & intStdID
cmd.ExecuteNonQuery()
'refresh data
Me.RefreshData()
'close connection
cnn.Close()
End If
End If
End Sub
End Class
OleDB uses a question mark ? character as a placeholder for parameters. If any of your textboxes contain a ?, then you will see the error you mention in the title.
As helrich said, you should parameterize your query. This will also prevent a SQL injection against your DB. (This goes for all of your queries, not just the Insert.)
Unrelated, but OleDBCommand implements the IDisposable interface, so you should also dispose it or use it inside of a using-block.
Using cmd As New OleDBCommand()
'... some code omitted for brevity ...
cmd.CommandText = "INSERT INTO student(stdid, stdname, gender, phone, address) VALUES(?, ?, ?, ?, ?);"
'Add the parameters specified.
'OleDB uses question marks as placeholders.
'Parameters must be added in the correct order.
cmd.Parameters.Add("stdid", txtstdID.Text)
cmd.Parameters.Add("stdname", txtStdName.Text)
cmd.Parameters.Add("gender", cboGender.Text)
cmd.Parameters.Add("phone", txtPhone.Text)
cmd.Parameters.Add("address", txtAddress.Text)
cmd.ExecuteNonQuery()
'... more code omitted for brevity ...
End Using

vb.net 2008 insertion command for ms access is not showing any error but not inserted into table

I written some code to insert data of form into ms access database
it runs successfully and gives no error
but when I see in data base I found there is no data inserted in the database.
what is the problem?
So guys, please help me.
Here is my vb.net code :
Private Sub btnCreateUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateUser.Click
Dim con2 As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\OfficeAutomationSystem.accdb; Persist Security Info=False")
Dim cmd As New OleDb.OleDbCommand
If Not con2.State = ConnectionState.Open Then
con2.Open()
End If
cmd.Connection = con2
'add data to table
cmd.CommandText = "INSERT INTO tblUser(emp_id, user_id, pwd, user_type) " & _
" values(" & Me.cbEmpId.SelectedItem & ", '" & Me.txtUserId.Text & "','" & _
Me.txtPassword.Text & "', '" & Me.cbUserType.SelectedItem & "')"
cmd.ExecuteNonQuery()
MsgBox("running")
End Sub
and here is my data base structure of ms access database :
field name dataYpe
serial_no AutoNumber
emp_id Number
user_id Text
pwd Text
user_type Text
Thanks in advance .
Can you try to execute this code and just let me know if it works
Private Sub btnCreateUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateUser.Click
Dim con2 As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\OfficeAutomationSystem.accdb; Persist Security Info=False")
Dim cmd As New OleDb.OleDbCommand
If Not con2.State = ConnectionState.Open Then
con2.Open()
End If
cmd.Connection = con2
'add data to table
cmd.CommandText = "INSERT INTO tblUser(emp_id, user_id, pwd, user_type) " & _
" values(" & Convert.ToInt32(Me.cbEmpId.SelectedItem) & ", '" & Me.txtUserId.Text & "','" & _
Me.txtPassword.Text & "', '" & Me.cbUserType.SelectedItem & "')"
cmd.ExecuteNonQuery()
MsgBox("running")
End Sub

Syntax error in UPDATE statement access database in vb.net

I have just started learning VB.net for several weeks. i want to make a form and send data from a text box to a specific cell in ms access database (*.accdb) file. but the code i have writen gives the following error:
Syntax error in UPDATE statement.
i have checked several books and spent hours on internet, but no answer!
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim cnn1 As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=
E:\Ebook\hararat\GUI\Heat Exchanger Designer\heat.accdb"
con.Open()
sql = "SELECT * FROM flow1"
da = New OleDbDataAdapter(sql, con)
da.Fill(ds, "flow1")
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("flow1").Rows(1).Item(1) = "name"
da.Update(ds, "flow1")
con.Close()
You need to use the .QuotePrefix and .QuoteSuffix properties of the OleDbCommandBuilder to wrap table and field names in square brackets. That is, instead of just
Dim cb As New OleDb.OleDbCommandBuilder(da)
you need to do
Dim cb As New OleDb.OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
That will generate an UPDATE statement of the form
UPDATE [TableName] SET [ColumnName]= ...
which is necessary if the table name or any of the field names happen to be reserved words in Access SQL.
Try this one
dim sqlupdate as string = "UPDATE tablename SET column_name = '" & textname.text & "' WHERE column_name = '" & textname.text & "'"
Sometimes errors occur when using the following column names: Username, Password, Date, Time, and much more of this type, try to avoid these column names because this might cause the problem of your issue regarding updating tables. Enable for you to update this kind of column name you need to enclose it with [ and ] so it comes like this: [Username], [Date], etc. so the syntax might go like this:
UPDATE tablename SET [Username] = '" & textname.text & "' WHERE column_name = '" & textname.text & "'"
my codes goes like this:
Open_Con()
Dim sqlUpdate As String
Dim sqlUpdatePass As DialogResult
sqlUpdate = "UPDATE tblAccounts SET [Password] = '" & txtRPassword.Text & "' WHERE [Username] = '" & txtUsername.Text & "'"
sqlCmd = New OleDbCommand(sqlUpdate, sqlCon)
Try
sqlUpdatePass = MessageBox.Show("Are you sure to save this changes?", "Save changes?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If sqlUpdatePass = vbYes Then
sqlCmd.ExecuteNonQuery()
MsgBox("Changes are now saved", MsgBoxStyle.Information, "New password has been set.")
Call ClearAll()
Me.Hide()
Else
Exit Sub
End If
Catch ex As Exception
MsgBox("Could not perform this task because " & ex.Message, MsgBoxStyle.Exclamation, "Error")
End Try
sqlCmd = Nothing
sqlCon.Close()
hope this things mention above codes helps your problem. have a nice day and happy coding :)
dim sqlupdate as string="UPDATE [tablename] SET [column_name] = '"& textname.text &"' WHERE [column_name] = '"& textname.text &"';"
By enclose attributes with square brackets, it appears to work I have tried it, it works
Imports System.Data.OleDb
Imports System.Data
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database2DataSet.identitas' table. You can move, or remove it, as needed.
Me.IdentitasTableAdapter.Fill(Me.Database2DataSet.identitas)
End Sub
Public Sub clean()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
End Sub
Public Sub read()
Call openconn()
str = "select * from identitas"
dtadapter = New OleDbDataAdapter(str, con)
Dim dg As New DataTable
dg.Clear()
dtadapter.Fill(dg)
dgv.DataSource = dg
End Sub
Public Sub create()
Call openconn()
str = "insert into identitas values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "') "
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
MsgBox("data lebet")
read()
clean()
End Sub
Public Sub update()
Call openconn()
str = "UPDATE identitas SET [Nama] = '" & TextBox2.Text & "',[Alamat] = '" & TextBox3.Text & "', [No] = '" & TextBox4.Text & "' where [NIK] = '" & TextBox1.Text & "'"
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
MsgBox("data ter ubah")
clean()
read()
End Sub
Public Sub delete()
Call openconn()
str = "delete from identitas where NIK = '" & TextBox1.Text & "'"
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
clean()
End Sub
Private Sub btnclose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclose.Click
Me.Close()
End Sub
Private Sub btnc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnc.Click
create()
End Sub
Private Sub btnr_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnr.Click
read()
End Sub
Private Sub btnclean_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclean.Click
clean()
End Sub
Private Sub btnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnd.Click
Dim pesan As String = MsgBox("yakin mau hapus = " & TextBox1.Text & "?", MsgBoxStyle.YesNo)
If pesan = vbYes Then
delete()
End If
read()
End Sub
Private Sub btnu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnu.Click
update()
End Sub
End Class
I had same problem, this helped.
"Sometimes errors occur when using the following column names: Username, Password, Date, Time, and much more of this type, try to avoid these column names because this might cause the problem of your issue regarding updating tables. Enable for you to update this kind of column name you need to enclose it with [ and ] so it comes like this: [Username], [Date], etc. so the syntax might go like this: "
I renamed the columns in Access (e.g Password1,Username1) as the same words password, username might be reserved in vb.net. Thanks for this response.