vb.net how to create the login permission - vb.net

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

Related

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

Visual Studio 2010 - Message Box popping up twice, why and how to fix?

I'm writing a small app that allows the user to return and update three types of labels based on searching by charting number, order number, or product ID. How the design works is that there is an input box where you input the either the charting number/order number/product id and specify by selecting one of three radio buttons corresponding to the above three choices for input. There are three boxes to the right of the input box that returns the label IDs of each type of label, and the contents of these box can be directly edited and updated by clicking on an update button. The problem is that the return message pops up twice after updating, which is a nuisance, so I was wondering where in my code should I change to resolve this issue? I will paste the full code below in case the problem is located somewhere I haven't expected:
Imports MySql.Data.MySqlClient
Public Class Form1
Dim dbconn As New MySqlConnection
Dim sql As String
Dim mycommand As New MySqlCommand
Dim mydata As MySqlDataReader
Public Sub myConnection()
dbconn = New MySqlConnection("Server=###;Database=###;Uid=###;Pwd=###;")
Try
dbconn.Open()
Catch ex As Exception
MsgBox("Connection Error: " & ex.Message.ToString)
End Try
End Sub
Private Sub chartNoSub()
myConnection()
sql = "SELECT pltlbl, cuslbl, boxlbl from formats as a join ordtab as b join chart as c where a.prodid=b.cusled and concat(b.ordno, b.orditm)=concat(c.ord01, c.oitm01) and c.chart='" & inputBox.Text & "'"
mycommand.Connection = dbconn
mycommand.CommandText = sql
mydata = mycommand.ExecuteReader
While (mydata.Read())
pltLBL.Text = mydata.Item("pltlbl")
cusLBL.Text = mydata.Item("cuslbl")
boxLBL.Text = mydata.Item("boxlbl")
End While
mydata.Close()
dbconn.Close()
End Sub
Private Sub ordNoSub()
myConnection()
sql = "SELECT pltlbl, cuslbl, boxlbl from formats as a join ordtab as b where a.prodid=b.cusled and concat(b.ordno, '-', b.orditm)='" & inputBox.Text & "'"
mycommand.Connection = dbconn
mycommand.CommandText = sql
mydata = mycommand.ExecuteReader
While (mydata.Read())
pltLBL.Text = mydata.Item("pltlbl")
cusLBL.Text = mydata.Item("cuslbl")
boxLBL.Text = mydata.Item("boxlbl")
End While
mydata.Close()
dbconn.Close()
End Sub
Private Sub prodIDsub()
myConnection()
sql = "select pltlbl, cuslbl, boxlbl from formats where prodid='" & inputBox.Text & "'"
mycommand.Connection = dbconn
mycommand.CommandText = sql
mydata = mycommand.ExecuteReader
While (mydata.Read())
pltLBL.Text = mydata.Item("pltlbl")
cusLBL.Text = mydata.Item("cuslbl")
boxLBL.Text = mydata.Item("boxlbl")
End While
mydata.Close()
dbconn.Close()
End Sub
Private Sub Input_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles inputBox.TextChanged
pltLBL.Clear()
cusLBL.Clear()
boxLBL.Clear()
If (inputBox.Text <> "" And prodID.Checked = False And ordNo.Checked = False And chart.Checked = False) Then MsgBox("Please select an option below before inputting.")
If prodID.Checked = True Then
prodIDsub()
End If
If ordNo.Checked = True Then
ordNoSub()
End If
If chart.Checked = True Then
chartNoSub()
End If
End Sub
Private Sub update_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles updateLBL.Click, updateLBL.Click
myConnection()
sql = "update formats as a inner join ordtab as b on a.prodid = b.cusled inner join chart as c on b.ordno=c.ord01 and b.orditm=c.oitm01 set a.pltlbl = '" & pltLBL.Text & "', a.cuslbl = '" & cusLBL.Text & "', a.boxlbl = '" & boxLBL.Text & "' where a.prodid = '" & inputBox.Text & "' or concat(b.ordno, '-', b.orditm)='" & inputBox.Text & "' or c.chart='" & inputBox.Text & "'"
mycommand.Connection = dbconn
mycommand.CommandText = sql
mycommand.CommandType = CommandType.Text
Dim rows = mycommand.ExecuteNonQuery()
If rows <> 0 Then
MessageBox.Show("Update successful!")
Else
MessageBox.Show("Check input.")
End If
dbconn.Close()
End Sub
Private Sub clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles clearLBL.Click
prodID.Checked = False
ordNo.Checked = False
chart.Checked = False
inputBox.Text() = ""
End Sub
End Class
Just to mark this as answered;
The solution was found, somewhat incredibly, by #GlorinOakenfoot.
The MsgBox was being called in Private Sub update_Click, but the Handles had the event happening twice on every click, hence the recursion of everything.

How to Refresh. Datagridview after adding data.im using sql database

below is my code for my project.
hope you can help me.
thanks in advance. :)
this is my sqlcontrol code
Imports System.Data
Imports System.Data.SqlClient
Public Class SQLControl
Public SQLCon As New SqlConnection With {.ConnectionString = "Server=xxx\SQLEXPRESS;Database=SQLTest;User=sa;Pwd=xxxx;"}
Public SQLCmd As SqlCommand 'allow us to fire query at the data base
Public SQLDA As SqlDataAdapter
Public SQLDataset As DataSet
Public dtable As New DataTable
Public bs As New BindingSource
'QUERY PARAMETERS
Public Params As New List(Of SqlParameter)
Public RecordCount As Integer
Public Exception As String
Public Function HasConnection() As Boolean
Try
SQLCon.Open()
SQLCon.Close()
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
Public Sub ExecQuery(ByVal Query As String)
Try
SQLCon.Open()
'CREATE SQL COMMAND
SQLCmd = New SqlCommand(Query, SQLCon)
'LOAD PARAMETER INTO SQL COMMAND
Params.ForEach(Sub(x) SQLCmd.Parameters.Add(x))
'CLEAR PARAMETER LIST
Params.Clear()
'EXCUTE COMMAND FILL MY DATASET
SQLDataset = New DataSet
'EXCUTE COMMAND WIHTOUT ADAPTER
SQLDA = New SqlDataAdapter(SQLCmd)
RecordCount = SQLDA.Fill(SQLDataset)
SQLCon.Close()
Catch ex As Exception
Exception = ex.Message
End Try
If SQLCon.State = ConnectionState.Open Then SQLCon.Close()
End Sub
Public Sub RunQuery(ByVal Query As String)
Try
SQLCon.Open()
SQLCmd = New SqlCommand(Query, SQLCon)
'LOAD SQL RECORDS FOR DATAGRID
SQLDA = New SqlDataAdapter(SQLCmd)
SQLDataset = New DataSet
SQLDA.Fill(SQLDataset)
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
If SQLCon.State = ConnectionState.Open Then
SQLCon.Close()
End If
End Try
End Sub
Public Sub AddMember(ByVal PC As String, ByVal IP As String, ByVal Name As String, ByVal Email As String, ByVal Department As String, ByVal Location As String,
ByVal Model As String, ByVal Specs As String, ByVal Dt As String, ByVal Asset As String, ByVal Rent As String)
Try
Dim strInsert As String = "INSERT INTO MEMBERS (pc,ip,name,email,department,location,model,specs,date,asset,rent) " & _
"VALUES (" & _
"'" & PC & "'," & _
"'" & IP & "'," & _
"'" & Name & "'," & _
"'" & Email & "'," & _
"'" & Department & "'," & _
"'" & Location & "'," & _
"'" & Model & "'," & _
"'" & Specs & "'," & _
"'" & Dt & "'," & _
"'" & Asset & "'," & _
"'" & Rent & "')"
MsgBox(strInsert)
SQLCon.Open()
SQLCmd = New SqlCommand(strInsert, SQLCon)
SQLCmd.ExecuteNonQuery()
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
And this is my form code:
Public Class Form1
Private SQL As New SQLControl
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'EXECUTE QUERY AND POPULATE GRID
SQL.ExecQuery("SELECT * FROM members")
LoadGrid()
'DISABLE SAVE BUTTON
cmdSave.Enabled = False
End Sub
Private Sub LoadGrid()
'IF OUR DATA IS RETURNED AND POPULATE GRID & BUILD UPDATE COMMAND
If SQL.RecordCount > 0 Then
dgvData.DataSource = SQL.SQLDataset.Tables(0)
dgvData.Rows(0).Selected = True
SQL.SQLDA.UpdateCommand = New SqlClient.SqlCommandBuilder(SQL.SQLDA).GetUpdateCommand
End If
End Sub
Private Sub dgvData_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvData.CellValueChanged
cmdSave.Enabled = True
End Sub
Private Sub dgvData_RowsRemoved(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsRemovedEventArgs) Handles dgvData.RowsRemoved
cmdSave.Enabled = True
End Sub
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
'SAVE UPDATE TO THE DATA BASE
Try
SQL.SQLDA.Update(SQL.SQLDataset) ' TO DO: DATA VALIDATION
Catch ex As Exception
MsgBox("Already Exists")
End Try
'REFRESH GRID DATA
LoadGrid()
'DISABLE SAVE BUTTON
cmdSave.Enabled = False
End Sub
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
If Trim(txtPC.Text) = "" Then
MsgBox("Please fill out the pc name.")
Exit Sub
End If
If Trim(txtIP.Text) = "" Then
MsgBox("Please fill out the ip address.")
Exit Sub
End If
'Query for user
SQL.RunQuery("SELECT * FROM members WHERE members.PC = '" & txtPC.Text & "'")
If SQL.SQLDataset.Tables(0).Rows.Count > 0 Then
MsgBox("The name that you have enter enter is already exists")
Exit Sub
End If
SQL.RunQuery("SELECT * FROM members WHERE members.IP = '" & txtIP.Text & "'")
If SQL.SQLDataset.Tables(0).Rows.Count > 0 Then
MsgBox("The IP Address that you have enter is already exists!")
Exit Sub
End If
SQL.RunQuery("SELECT * FROM members WHERE members.Asset = '" & txtAsset.Text & "'")
If SQL.SQLDataset.Tables(0).Rows.Count > 0 Then
MsgBox("The Asset that you have enter is already exists")
Exit Sub
Else
CreateUser()
txtPC.Clear()
txtIP.Clear()
txtName.Clear()
txtEmail.Clear()
txtDepartment.Clear()
txtLocation.Clear()
txtModel.Clear()
txtSpecs.Clear()
txtDt.Clear()
txtAsset.Clear()
txtRent.Clear()
End If
End Sub
Public Sub CreateUser()
SQL.AddMember(txtPC.Text, txtIP.Text, txtName.Text, txtEmail.Text, txtDepartment.Text,
txtLocation.Text, txtModel.Text, txtSpecs.Text, txtDt.Text, txtAsset.Text, txtRent.Text)
End Sub
End Class
I don't know how to refresh the datagridview
this will works. just
Copy And Paste this to your load form.
Public Sub RefreshUserGrid()
' RUN QUERY
SQL.ExecQuery("SELECT * FROM members")
If SQL.SQLDataset.Tables.Count > 0 Then
dgvData.DataSource = SQL.SQLDataset.Tables(0)
dgvData.Rows(0).Selected = True
End If
End Sub
and also copy and paste this RefreshUserGrid() at your add command.

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.

Database not Updating 1000

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.