Avoid duplicate data using vb.net and ms access - vb.net

what can I use if I want to put a message box saying the data is already exist.
Here is my code.
Private Sub bttnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttnSave.Click
con.Open()
Dim fname As String = Trim(txtFName.Text)
Dim mname As String = Trim(txtMName.Text)
Dim lname As String = Trim(txtLName.Text)
Dim add As String = Trim(txtAddress.Text)
Dim num As String = Trim(txtNumber.Text)
Dim email As String = Trim(txtEmail.Text)
Dim stat As String = "Active"
Dim remark As String = "Available"
If fname = Nothing Or mname = Nothing Or lname = Nothing Or add = Nothing Or num = Nothing Then
MsgBox("Please Fill All Fields", vbInformation, "Note")
Else
Dim add_guest As New OleDbCommand("INSERT INTO tblGuest(GuestFName,GuestMName,GuestLName,GuestAddress,GuestContactNumber,GuestGender,GuestEmail,Status,Remarks) values ('" &
fname & "','" &
mname & "','" &
lname & "','" &
add & "','" &
num & "','" &
cboGender.Text & "','" &
email & "','" &
stat & "','" &
remark & "')", con)
add_guest.ExecuteNonQuery()
add_guest.Dispose()
MsgBox("Guest Added!", vbInformation, "Note")
txtFName.Clear()
txtMName.Clear()
txtLName.Clear()
txtAddress.Clear()
txtNumber.Clear()
txtEmail.Clear()
End If
con.Close()
display_guest()
End Sub

Yes, as #Steve said, add Primary or Unique key for tblGuest for column email. Then check the existence of the record before executing insert statement.
Primary key - Add Primary key
Check exists or not - Check exists or not 1
Check exists or not 2

Related

how to save (insert) data in datatable from datagridview in vb.net step by step

I am creating code for inserting data from datagridview in vb.net to database table Access 2007. But the program is for inserting data from user when he input data in datagridview in 1st row then after next time (after break by break) he input data again on 2nd , 3rd next row and click on save button in my project to insert data in database.
but problem arises when he click on save 2nd time for inserting data into database the process code insert all row old & new again. it is not proper inserting. it repeats data.
So please suggest me Solution
I am using dt for datatable and sql for sql statement.
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim sql = "SELECT * FROM RABill "
maxrow = get_maxrow(sql)
For i = 0 To DgRAbill.Rows.Count - 2
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM RABill ")
Dim strInsert As String = "INSERT INTO RABill (Billnumber,RDate,RAmount,Below,Royalti,SD,IT,GSTminus,RAccountname,GstTwelvepercent,Insurance,Other,TotalBill,Remark) VALUES ('" _
& CStr(DgRAbill.Rows(i).Cells(1).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(2).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(3).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(4).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(5).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(6).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(7).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(8).FormattedValue) & "','" _
& ComboBox1.Text & "','" _
& CStr(DgRAbill.Rows(i).Cells(10).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(11).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(12).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(13).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(14).FormattedValue) & "')"
cmd = New OleDbCommand(strInsert, conn)
cmd.ExecuteNonQuery()
MsgBox("Record Saved Successfully")
Next
End Sub
in above code my datagridview has extra row in it so it code is rows-2
You don't appear to be clearing the variable 'strInsert' after the insert so this may be the issue you are facing?
I would be tempted to clear the variable after the MsgBox.
Many Thanks
POC
There are a couple of concerning things with your code snippet here.
Is your database suppose to be able to have duplicate entries? You might want to look at how your primary keys are set up.
You should really have some error catching in here, especially with database connections. Take a look through this for reference : https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/try-catch-finally-statement
As for the actual double entry - you're not clearing out your datagridview after saving all the records. If I'm understanding correctly the user fills in a bunch of rows in the DGV then hits save and it loops through and inserts them all. Then he continues entering and hits save again and it inserts all of them (some duplicates). After saving you should do a .Clear on your DGV - or you need to create some kind of counter that persists between saves and that's where you'll start your for loop at in the save button Below is clearing it after each save:
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim sql = "SELECT * FROM RABill "
maxrow = get_maxrow(sql)
For i = 0 To DgRAbill.Rows.Count - 2
Try
Dim strInsert As String = "INSERT INTO RABill (Billnumber,RDate,RAmount,Below,Royalti,SD,IT,GSTminus,RAccountname,GstTwelvepercent,Insurance,Other,TotalBill,Remark) VALUES ('" _
& CStr(DgRAbill.Rows(i).Cells(1).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(2).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(3).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(4).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(5).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(6).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(7).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(8).FormattedValue) & "','" _
& ComboBox1.Text & "','" _
& CStr(DgRAbill.Rows(i).Cells(10).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(11).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(12).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(13).FormattedValue) & "','" _
& CStr(DgRAbill.Rows(i).Cells(14).FormattedValue) & "')"
cmd = New OleDbCommand(strInsert, conn)
cmd.ExecuteNonQuery()
MsgBox("Record Saved Successfully")
DgRabill.Rows.Clear()
Catch ex As Exception
MessageBox.Show("Error Inserting record at row " & i & vbCrLf & ex.Message)
End Try
Next
End Sub
You can use following code to bind and save your DataGridView data to your database.
Dim connString As String = ""
Private ds As DataSet
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ds = New DataSet()
Using con As SqlConnection = New SqlConnection(connString)
con.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter("select * from RABill", con)
adp.Fill(ds)
Dim dt As DataTable = ds.Tables(0)
DataGridView1.DataSource = dt
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using con As SqlConnection = New SqlConnection(connString)
con.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter("select * from RABill", con)
Dim build As SqlCommandBuilder = New SqlCommandBuilder(adp)
adp.Update(ds.Tables(0))
End Using
End Sub
Whatever you edit in your DataGridView, click button1 those records will be saved in the database.

Register VB.Net Using Access Database

i have a problem regarding register form which i try to make it send to database ( add new record ) using data provided but its not working. Thank you very much
Here is the UI :
Heres my code :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim nama, uname, password, email, jk As String
Dim idusr As Integer
nama = TextBox1.Text
uname = TextBox2.Text
password = TextBox3.Text
email = TextBox5.Text
jk = ComboBox1.SelectedValue
Randomize()
' The program will generate a number from 0 to 50
idusr = Int(Rnd() * 50) + 1
If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or TextBox4.Text = "" Or TextBox5.Text = "" Then
MsgBox("Please Fill All The Box First !!!")
ElseIf TextBox3.Text <> TextBox4.Text Or TextBox3.TextLength <= 8 Then
MsgBox("Password do not match or missing !!!")
Else
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Michael\Tugas Materi Kuliah\VB\TA\DBUtama.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim str = "Insert into [User]([IDUSR],[Nama],[Uname],[Pass],[Jenis Kelamin],[Email]) Values ('" & idusr & "','" & nama & "','" & uname & "','" & password & "','" & jk & "','" & email & "') ;"
Dim cmd As OleDbCommand = New OleDbCommand(str, conn)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
Catch ex As Exception
MsgBox("Something broke, i know its you !!")
End Try
End If
End Sub
and Database :
idusr is numeric, thus no quotes:
Dim str = "Insert into [User]([IDUSR],[Nama],[Uname],[Pass],[Jenis Kelamin],[Email]) Values (" & idusr & ",'" & nama & "','" & uname & "','" & password & "','" & jk & "','" & email & "') ;"
And do leave out all those exclamation marks. Users are not idiots.
Also, get someone to proofread the prompts and captions.

Incorrect syntax error near 'email'

I'm running Visual studio and whenever I run my application it says "Incorrect syntax error near '(the email i enter appears here)'". I hope you can spot the mistake.
Within SQL server, my email column is called 'email'
Within Visual studio, the name of the input field for my email is called 'textEmail'
Public Sub AddCustomer(Firstname As String, Surname As String, Contactnum As String, Email As String)
Try
Dim strInsert As String = "INSERT INTO customers (firstname, surname, contactnum, email) " & _
"VALUES (" & _
"'" & Firstname & "'," & _
"'" & Surname & "'," & _
"'" & Contactnum & "'," & _
"'" & Email & "'"
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
Code within form:
Private Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
'QUERY FOR CUSTOMER
SQL.RunQuery("SELECT * FROM customers WHERE customers.email = '" & txtEmail.Text & "' ")
If SQL.SQLDS.Tables(0).Rows.Count > 0 Then
MsgBox("This Email alredy exists!")
Exit Sub
Else
CreateCustomer()
End If
End Sub
Public Sub CreateCustomer()
' ADD CUSTOMER TO DATABASE
SQL.AddCustomer(txtFirst.Text, txtSur.Text, txtNum.Text, txtEmail.Text)
End Sub
End Class
Thanks for your time.
You are missing closing bracket
Dim strInsert As String = "INSERT INTO customers (firstname, surname, contactnum, email) " & _
"VALUES (" & _
"'" & Firstname & "'," & _
"'" & Surname & "'," & _
"'" & Contactnum & "'," & _
"'" & Email & "')"

vb.net Syntax error in INSERT INTO Statement with access

I'm getting an error during my insert can someone take a look?
Table:
VB.NET
Dim Name As String = txtName.Text
Dim JoinDate As String = dpJoinDate.Value
Dim DOB As String = dpDOB.Value
Dim ParentsName As String = txtParentsName.Text
Dim School As String = txtSchool.Text
Dim STD As String = txtSTD.Text
Dim Address As String = txtAddress.Text
Dim EMail As String = txtEMail.Text
Dim Mobile1 As String = txtMobile1.Text
Dim Mobile2 As String = txtMobile2.Text
Dim DurationStart As Date = dpDurationStart.Value
Dim DurationEND As Date = dpDurationEND.Value
Dim Fees As Decimal = Decimal.Parse(0.0)
Dim MaterialFees As Decimal = Decimal.Parse(0.0)
Dim LateFees As Decimal = Decimal.Parse(0.0)
Dim NextRenewal As Date = dpNextRenewal.Value
Dim Centre As String = cbCentre.Text
Dim Coach As String = cbCoach.Text
Dim picture As String = lblFileName.Text
Try
Fees = Decimal.Parse(txtFees.Text)
Catch
End Try
Try
MaterialFees = Decimal.Parse(txtMaterialFees.Text)
Catch
End Try
Try
LateFees = Decimal.Parse(txtLateFees.Text)
Catch
End Try
Dim Cmd As OleDbCommand
Dim SQL As String
Dim objCmd As New OleDbCommand
Dim Con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=./AcademyDatabase.accdb;Persist Security Info=False;")
SQL = "INSERT INTO Student (FullName,JoinDate,DOB,ParentsName,School,STD,Address,EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees,MaterialFees,LateFees,NextRenewal,Centre,Coach,Image,DropOut) VALUES ('" _
& Name & "','" _
& JoinDate & "','" _
& DOB & "','" _
& ParentsName & "','" _
& School & "','" _
& STD & "','" _
& Address & "','" _
& EMail & "','" _
& Mobile1 & "','" _
& Mobile2 & "','" _
& DurationStart & "','" _
& DurationEND & "','" _
& Fees & "','" _
& MaterialFees & "','" _
& LateFees & "','" _
& NextRenewal & "','" _
& Centre & "','" _
& Coach & "','" _
& picture & "'," _
& "0)"
Cmd = New OleDbCommand(SQL, Con)
Con.Open()
objCmd = New OleDbCommand(SQL, Con)
Dim rowCount As Integer = 0
Try
rowCount = objCmd.ExecuteNonQuery()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Sql:
"INSERT INTO Student (FullName,JoinDate,DOB,ParentsName,School,STD,Address,EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees,MaterialFees,LateFees,NextRenewal,Centre,Coach,Image,DropOut) VALUES ('','3/13/2014','1/1/1900','','fadsasdffdas','','','','','','1/1/1900','1/1/1900','0','0','0','1/1/1900','','','',0)"
IMAGE is a reserved keyword. If you want to use it for a column name, then your need to encapsulate it with square brackets
"INSERT INTO Student " & _
"(FullName,JoinDate,DOB,ParentsName,School,STD,Address," & _
"EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees," & _
"MaterialFees,LateFees,NextRenewal,Centre,Coach,[Image],DropOut) VALUES ...."
If you are still able to do so, I suggest to change the name of that column to a NON reserved keyword, otherwise you will alway have this problem when you try to use that column.
Said that, please, read about parameterized queries. Your code has a big problem and it is called SQL Injection (not to mention the parsing problems for strings, date and decimals)
SQL = "INSERT INTO Student " & _
"(FullName,JoinDate,DOB,ParentsName,School,STD,Address," & _
"EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees," & _
"MaterialFees,LateFees,NextRenewal,Centre,Coach,[Image],DropOut) " & _
"?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0)"
Con.Open()
objCmd = New OleDbCommand(SQL, Con)
objCmd.Parameters.AddWithValue("#p1", Name)
objCmd.Parameters.AddWithValue("#p2", JoinDate)
.... add the other missing parameters with their values.....
objCmd.Parameters.AddWithValue("#p18", picture)
Dim rowCount As Integer = 0
rowCount = objCmd.ExecuteNonQuery()

Visual Studio 2010 insert syntax error again and again while inserting value to .mdb file

what is missing in insert statement ? the full code is now here. i cant add new fields values to .mdb file. it took 3 days to develop this app and now its not running.
what is missing in insert statement ? the full code is now here. i cant add new fields values to .mdb file. it took 3 days to develop this app and now its not running.
Public Class client
Dim cnn As New OleDb.OleDbConnection
Private Sub reloaddata()
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("select * from clientsData", cnn)
Dim dt As New DataTable
da.Fill(dt)
Me.cview.DataSource = dt
cnn.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
display.Hide()
cnn = New OleDb.OleDbConnection
cnn.ConnectionString = "provider= microsoft.jet.oledb.4.0; data source=" & Application.StartupPath & "\clients.mdb"
Me.reloaddata()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
display.Show()
End Sub
Private Sub cview_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles cview.CellClick
If cnn.State = ConnectionState.Closed Then
cnn.Open()
End If
Dim i As Integer
i = cview.CurrentRow.Index
If cview.CurrentCell.Value Is Nothing Then
MsgBox("Empty Field")
Else
view.lbl1.Text = cview.Item(0, i).Value.ToString
view.lbl2.Text = cview.Item(1, i).Value.ToString
view.lbl3.Text = cview.Item(2, i).Value.ToString
view.lbl4.Text = cview.Item(3, i).Value.ToString
view.lbl5.Text = cview.Item(4, i).Value.ToString
view.lbl6.Text = cview.Item(5, i).Value.ToString
view.lbl7.Text = cview.Item(6, i).Value.ToString
view.lbl8.Text = cview.Item(11, i).Value.ToString
view.lbl9.Text = cview.Item(12, i).Value.ToString
view.lbl10.Text = cview.Item(7, i).Value.ToString
view.lbl11.Text = cview.Item(8, i).Value.ToString
view.lbl12.Text = cview.Item(9, i).Value.ToString
view.lbl13.Text = cview.Item(10, i).Value.ToString
view.lbl14.Text = cview.Item(13, i).Value.ToString
view.Show()
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
cmd.CommandText = "insert into clientsdata(ID,Client,Project,Domain,Hosting,bulk sms,maintenance,Order date,amount,last billing,next billing,username,password,due amount) VALUES ('" & Me.cid.Text & "','" & Me.cname.Text & "','" & Me.cproj.Text & "','" & Me.cdmn.Text & "','" & Me.chost.Text & "','" & Me.csms.Text & "','" & Me.cmain.Text & "','" & Me.codt.Text & "','" & Me.camnt.Text & "','" & Me.cldt.Text & "','" & Me.cndt.Text & "','" & Me.cuid.Text & "','" & Me.cpass.Text & "','" & Me.cdue.Text & "' )"
cmd.ExecuteNonQuery()
Me.reloaddata()
cnn.Close()
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
cid.Text = "cid"
cname.Text = "cname"
cproj.Text = "cpro"
cdmn.Text = "domain"
chost.Text = "chost"
csms.Text = "sms"
cmain.Text = "main"
codt.Text = "codt"
camnt.Text = "mount"
cldt.Text = "last"
cndt.Text = "next"
cdue.Text = "due"
cuid.Text = "uid"
cpass.Text = "pass"
End Sub
End Class
ok problem solved !! I just added [ ] in the fields.
source: (VB.NET)Syntax Error in INSERT INTO statement - MICROSOFT JET DATABASE ENGINE
cmd.CommandText = "insert into clientsdata([ID],[Client],[Project],[Domain],[Hosting],[bulk sms],[maintenance],[Order date],[amount],[last billing],[next billing],[username],[password],[due amount]) VALUES (" & Me.cid.Text & ",'" & Me.cname.Text & "','" & Me.cproj.Text & "','" & Me.cdmn.Text & "','" & Me.chost.Text & "','" & Me.csms.Text & "','" & Me.cmain.Text & "','" & Me.codt.Text & "','" & Me.camnt.Text & "','" & Me.cldt.Text & "','" & Me.cndt.Text & "','" & Me.cuid.Text & "','" & Me.cpass.Text & "','" & Me.cdue.Text & "' )"
Your date field is a keyword. You have to place it with brackets: [date]. Also, any field names that have spaces require brackets, too: [Order date].
You really should use parameters to avoid SQL injection and to solve a host of other issues with updating databases.
I would also avoid trying to manage the connection state of the database. Just use the Using syntax so that the connection always closes.
If Me.cid.Text = "" Then
MessageBox.Show("Please input values")
Else
Using con As New OleDb.OleDbConnection("...")
con.Open()
Using cmd As New OleDb.OleDbCommand()
cmd.Connection = con
cmd.CommandText = "..."
cmd.Parameters.AddWithValue("#ID", Me.cid.Text)
cmd.Parameters.AddWithValue(...more)
cmd.ExecuteNonQuery()
End Using
End Using
reloaddata()
End If
It's hard to say what the problem is without knowing what is contained in each of the .Text values, and without seeing the definition of the table you are filling in. But I could hazard a guess that the Me.camnt.Text and Me.cdue.Text probably don't want to be surrounded by single quotes; that is to say, you may need something like this...
Me.codt.Text & "'," & Me.camnt.Text & ",'" & Me.cldt.Text
and
Me.cndt.Text & "'," & Me.cdue.Text & ",'" & Me.cuid.Text