update and delete is not working vb.net - sql-server

im having a problem in my codes there's no error showing up and when i press the button nothing happens this is the code im using first one is the update button
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Try
con.Open()
With cmd
.Connection = con
.CommandText = ("Update TBL_EMPLOYEE MiddleName='" & txtMiddleName.Text & "',LastName='" & txtLastName.Text & "', Gender='" & txtGender.Text & "',Age='" & txtupAge.Text & "' ,Address='" & txtupAddress.Text & "', Position='" & txtPos.Text & "',BirthDate='" & Bdate.Text & "' where [FirstName]=#FirstName ")
.Parameters.AddWithValue("FirstName", (txtFirstName.Text))
.ExecuteNonQuery()
.Dispose()
txtFirstName.Text = ""
txtMiddleName.Text = ""
txtLastName.Text = ""
txtGender.Text = ""
txtContactNumber.Text = ""
txtupAge.Text = ""
txtupAddress.Text = ""
txtPos.Text = ""
Bdate.Text = ""
PictureBox2.Image = Nothing
MsgBox("Product Updated", vbInformation, "Information Message")
datagridshow()
End With
Catch ex As Exception
End Try
End Sub
there's no error showing up in the code and nothing happening when i pressed the button and same with my delete button
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
con.Open()
With cmd
.Connection = cn
.CommandText = "DELETE * from [TBL_EMPLOYEE] where FirstName='" & DataGridView2.CurrentRow.Cells(1).Value.ToString & "' "
.ExecuteNonQuery()
.Dispose()
.Parameters.Clear()
txtFirstName.Text = ""
txtMiddleName.Text = ""
txtLastName.Text = ""
txtGender.Text = ""
txtContactNumber.Text = ""
txtupAge.Text = ""
txtupAddress.Text = ""
txtPos.Text = ""
Bdate.Text = ""
PictureBox2.Image = Nothing
MsgBox("Employee Deleted", MsgBoxStyle.Information)
datagridshow()
End With
Catch ex As Exception
End Try
End Sub
there's no error and nothing happen also here
this is the form load i am using.
Dim str As String
str = ("Server=LOCALHOST\SQLEXPRESS;Database=Payroll;Trusted_Connection=True;")
cn = New SqlConnection(Str)
cn.Open()

Your UPDATE is missing the SET keyword, and your DELETE has a * that shouldn't be there.

Related

New form is not blank when loaded, contains data from previous transaction

I have a winforms app that connects to a SQL Server database. On the form to add a new golfer to the golfers table, there are combo boxes for t-shirt size and gender. When a new record is submitted, all the inputs are supposed to clear so that the form is blank when it is re-initialized to add the next record.
The problem is that, when the form is re-initialized, the previously added golfer's gender and t-shirt size are still in their respective combo boxes, while every other input is blank. I've gone through the code, and there's nothing in the load event for the form that would do this. How can I fix this?
Here is my code:
'Button on main form to open the input form to add new golfer
Private Sub btnAddGolfer_Click(sender As Object, e As EventArgs) Handles btnAddGolfer.Click
'Show Form To Add New Golfer
frmAddGolfer.ShowDialog()
'Refresh Form
frmManageGolfers_Load(sender, e)
End Sub
_______________________________________________________________
Private Sub frmAddGolfer_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Clear any previous data
ClearForm()
End Sub
______________________________________________________________
'load event for input form
Private Sub btnAddGolfer_Click(sender As Object, e As EventArgs) Handles btnAddGolfer.Click
Dim strSelectPlayerID As String = ""
Dim dtDataTable As DataTable = New DataTable
Dim strFirstName As String = ""
Dim strLastName As String = ""
Dim strStreetAddress As String = ""
Dim strCity As String = ""
Dim strState As String = ""
Dim strZip As String = ""
Dim strPhoneNumber As String = ""
Dim strEmail As String = ""
Dim intGenderID As Integer
Dim intShirtSizeID As Integer
Dim intRowsAffected As Integer
Dim intNextHighestRecordID As Integer
'Reset control colors
txtFirstName.BackColor = Color.White
txtLastName.BackColor = Color.White
txtAddress.BackColor = Color.White
txtCity.BackColor = Color.White
txtState.BackColor = Color.White
txtZip.BackColor = Color.White
txtPhoneNumber.BackColor = Color.White
txtEmailAddress.BackColor = Color.White
cboGender.BackColor = Color.White
cboShirtSizes.BackColor = Color.White
' this will hold our EXECUTE statement
Dim cmdAddPlayer As OleDb.OleDbCommand
' check to make sure all fields have data. No data no update!
If Validation(txtFirstName.Text, txtLastName.Text, txtAddress.Text, txtCity.Text, txtState.Text, txtZip.Text, txtPhoneNumber.Text, txtEmailAddress.Text, CStr(cboGender.SelectedItem), CStr(cboShirtSizes.SelectedItem)) = True Then
' open database
If OpenDatabaseConnectionSQLServer() = False Then
' No, warn the user ...
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
' and close the form/application
Me.Close()
End If
Try
' make the connection
cmdAddPlayer = New OleDb.OleDbCommand()
'Set Values For stored procedure parameters
strFirstName = txtFirstName.Text
strLastName = txtLastName.Text
strStreetAddress = txtAddress.Text
strCity = txtCity.Text
strState = txtState.Text
strZip = txtZip.Text
strPhoneNumber = txtPhoneNumber.Text
strEmail = txtEmailAddress.Text
intGenderID = CInt(cboGender.SelectedIndex) + 1
intShirtSizeID = CInt(cboShirtSizes.SelectedIndex) + 1
' Build the select statement using PK from name selected
' Text to build call to stored proc
cmdAddPlayer.CommandType = CommandType.StoredProcedure
cmdAddPlayer.CommandText = "EXECUTE uspAddGolfer '" &
intNextHighestRecordID & "', " &
"'" & strFirstName & "', " &
"'" & strLastName & "', " &
"'" & strStreetAddress & "', " &
"'" & strCity & "', " &
"'" & strState & "', " &
"'" & strZip & "', " &
"'" & strPhoneNumber & "', " &
"'" & txtEmailAddress.Text & "', " &
"'" & intGenderID & "', " &
"'" & intShirtSizeID & "'"
'EXECUTE stored proc
cmdAddPlayer = New OleDb.OleDbCommand(cmdAddPlayer.CommandText, m_conAdministrator)
' Update the row with execute the statement
intRowsAffected = cmdAddPlayer.ExecuteNonQuery()
' have to let the user know what happened
If intRowsAffected = 1 Then
MessageBox.Show("New record added successfully")
'clear inputs and close form
ClearForm()
Me.Close()
Else
MessageBox.Show("Update failed")
'clear inputs and close form
ClearForm()
Me.Close()
End If
' close the database connection
CloseDatabaseConnection()
Catch Ex As Exception
'Display Error Message To User
MessageBox.Show(Ex.Message)
End Try
End If
End Sub
______________________________________________________________
Private Sub ClearForm()
'Clear form and reset control colors
txtFirstName.Clear()
txtLastName.Clear()
txtAddress.Clear()
txtCity.Clear()
txtState.Clear()
txtZip.Clear()
txtPhoneNumber.Clear()
txtEmailAddress.Clear()
cboGender.ResetText()
cboShirtSizes.ResetText()
txtFirstName.BackColor = Color.White
txtLastName.BackColor = Color.White
txtAddress.BackColor = Color.White
txtCity.BackColor = Color.White
txtState.BackColor = Color.White
txtZip.BackColor = Color.White
txtPhoneNumber.BackColor = Color.White
txtEmailAddress.BackColor = Color.White
cboGender.BackColor = Color.White
cboShirtSizes.BackColor = Color.White
End Sub
The fact that you're calling an event handler directly is a good indication that you're doing it wrong. Don't use default instances at all. Just do it properly and create a new instance each time. That way, the load event handler will be executed naturally as a result of the form being loaded. Create the form with a Using statement so it is disposed when you're done with it.
Using dialogue As New frmAddGolfer
dialogue.ShowDialog()
End Using
If you do it this way, there will be no need to clear the form anyway, because it will be a new form.
The following code seems to do the trick.
Private Sub frmAddGolfer_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
ComboBox1.SelectedIndex = -1
ComboBox2.SelectedIndex = -1
End Sub
I am not familiar with ResetText.
Now, to your data access code. Keep your data objects local so you can control that they are closed and disposed. This is especially important for connections which are precious resources. Using...End Using blocks will do this for you even if there is an error.
Private Sub btnAddGolfer_Click(sender As Object, e As EventArgs) Handles btnAddGolfer.Click
Dim intRowsAffected As Integer
' check to make sure all fields have data. No data no update!
If Not Validation(txtFirstName.Text, txtLastName.Text, txtAddress.Text, txtCity.Text, txtState.Text, txtZip.Text, txtPhoneNumber.Text, txtEmailAddress.Text, CStr(cboGender.SelectedItem), CStr(cboShirtSizes.SelectedItem)) Then
MessageBox.Show("All data must be filled in.")
Return
End If
Using cn As New SqlConnection("Your connection string")
Using cmdAddPlayer As New SqlCommand("uspAddGolfer", cn)
cmdAddPlayer.CommandType = CommandType.StoredProcedure
cmdAddPlayer.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text
cmdAddPlayer.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLastName.Text
cmdAddPlayer.Parameters.Add("#Address", SqlDbType.VarChar).Value = txtAddress.Text
cmdAddPlayer.Parameters.Add("#City", SqlDbType.VarChar).Value = txtCity.Text
cmdAddPlayer.Parameters.Add("#State", SqlDbType.VarChar).Value = txtState.Text
cmdAddPlayer.Parameters.Add("#Zip", SqlDbType.VarChar).Value = txtZip.Text
cmdAddPlayer.Parameters.Add("#Phone", SqlDbType.VarChar).Value = txtPhoneNumber.Text
cmdAddPlayer.Parameters.Add("#Email", SqlDbType.VarChar).Value = txtEmailAddress.Text
cmdAddPlayer.Parameters.Add("#Gender", SqlDbType.Int).Value = cboGender.SelectedIndex + 1 'Index is an Integer
cmdAddPlayer.Parameters.Add("#ShirtSize", SqlDbType.Int).Value = cboShirtSizes.SelectedIndex + 1
cn.Open()
intRowsAffected = cmdAddPlayer.ExecuteNonQuery()
End Using
End Using
If intRowsAffected = 1 Then
MessageBox.Show("New record added successfully")
Close()
Else
MessageBox.Show("Update failed")
Close()
End If
End Sub
You will have to check your stored procedure to get the correct parameter names and data types.

I want to update my data of my database in VB.net but I get Error Syntax

This is my problem:
When I click update button, I don't know how to fix this error:
My Error Message is:
"Error: syntax error in union query"
This is my code:
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
TestConnection()
Try
Dim cmd As OleDbCommand
Dim sql As String
sql = "(UPDATE tblUsers SET Username = '" & txtUserName.Text & "', Password = '" & txtUserPassword.Text &
"', Usertype = '" & cbousertype.Text & "', WHERE UserID = '" & txtUserID.Text & "');"
cmd = New OleDbCommand(sql, Conn)
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Error: " & ex.Message)
End Try
End Sub
Is it wrong?
Now my problem has been solved thank you very much
i changed my code to use a parameters and then it work
Now my code is :
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
TestConnection()
Dim cmd As OleDbCommand
Dim sql As String
sql = "UPDATE tblUsers SET Username=?, [Password]=?, Usertype=? where UserID=?"
cmd = New OleDbCommand(sql, Conn)
cmd.Parameters.AddWithValue("#p1", txtUserName.Text)
cmd.Parameters.AddWithValue("#p2", txtUserPassword.Text)
cmd.Parameters.AddWithValue("#p3", cbousertype.Text)
cmd.Parameters.AddWithValue("#p4", txtUserID.Text)
cmd.ExecuteNonQuery()
MsgBox("Data Has Been Updated", MsgBoxStyle.Information, "Updated")
ShowUser()
End Sub

Populating combobox in VB from SQL Server database

I have actually done some research on this, and result is shown in my work. But I am still having problems populating the combobox. The form runs fine with no errors, but nothing shows up in the combobox. Can anyone help with this issue? I keep running it over, but I have absolutely no idea where the problem is.
Public Class Form1
Private Sub cboModel_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboModel.SelectedIndexChanged
Try
Dim strSelect As String = ""
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim dt As DataTable = New DataTable
If OpenDatabaseConnectionSQLServer() = False Then
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
cboModel.BeginUpdate()
cboModel.Items.Clear()
strSelect = "SELECT intAutoID, strMake FROM TAutos"
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
dt.Load(drSourceTable)
cboModel.ValueMember = "intAutoID"
cboModel.DisplayMember = "strMake"
cboModel.DataSource = dt
If cboModel.Items.Count > 0 Then cboModel.SelectedIndex = 0
cboModel.EndUpdate()
drSourceTable.Close()
CloseDatabaseConnection()
Catch excError As Exception
MessageBox.Show(excError.Message)
End Try
End Sub
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Dim strSelect As String = ""
Dim strModel As String = ""
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim dt As DataTable = New DataTable
If OpenDatabaseConnectionSQLServer() = False Then
MessageBox.Show(Me, "Database Connection Error." & vbNewLine &
"The Application Will Now Close.",
Me.Text + "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
strSelect = "SELECT strMake, strModel, strYear, strMileage FROM TAutos WHERE intAutoID = " & cboModel.SelectedValue
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
dt.Load(drSourceTable)
txtMake.Text = dt.Rows(0).Item(0)
txtMileage.Text = dt.Rows(1).Item(1)
txtYear.Text = dt.Rows(2).Item(2)
CloseDatabaseConnection()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Close()
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim strSelect As String = ""
Dim strMake As String = ""
Dim strMileage As String = ""
Dim strYear As String = ""
Dim intRowsAffected As Integer
Dim cmdUpdate As OleDb.OleDbCommand
If OpenDatabaseConnectionSQLServer() = False Then
MessageBox.Show(Me, "Database Connection Error." & vbNewLine &
"The Application Will Now Close.",
Me.Text + "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
strMake = txtMake.Text
strMileage = txtMileage.Text
strYear = txtYear.Text
strSelect = "Update TAutos Set strMake = '" & strMake & "', " & "strMileage = '" & strMileage & "', " & "strYear = '" & strYear & "', " & "Where intAutoID = " & cboModel.SelectedValue
MessageBox.Show(strSelect)
cmdUpdate = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
intRowsAffected = cmdUpdate.ExecuteNonQuery()
If intRowsAffected = 1 Then
MessageBox.Show("Update Failed")
End If
CloseDatabaseConnection()
End Sub
End Class

search read sql data to textbox in vb

it show even when i have data inside my database[invalid attempt to read when no data is present]
i was hoping to show details in textbox with txtid.text inserted
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
Try
con.ConnectionString = "Server=KAVIER;Database=vb;Trusted_Connection=True;"
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT * FROM music where mus_id = '" & txtid.Text & "' "
rd = cmd.ExecuteReader() 'corrected my previous mistake
If rd.HasRows Then
txtartist.Text = rd.Item("customer")
txtid.Text = rd.Item("album")
txtgenre.Text = rd.Item("genre")
hided.Text = rd.Item("music_copies")
txtprice.Text = rd.Item("price")
txttotal.Text = txtprice.Text * txtwalkinquantities.Text
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
cmd.CommandText = "SELECT * FROM music where mus_id = '" & txtid.Text & "' "
rd = cmd.ExecuteReader()
If rd.read Then
txtartist.Text = rd.Item("customer")
txtid.Text = rd.Item("album")
txtgenre.Text = rd.Item("genre")
hided.Text = rd.Item("music_copies")
txtprice.Text = rd.Item("price")
txttotal.Text = txtprice.Text * txtwalkinquantities.Text
End If
replace rd.HasRows with rd.read

VB.NET database data passing error

I get the error message
"Error while inserting record o the table… Incorrect syntax near the
keyword ‘return’.Incorrect syntax near ‘,’ ."
Public Class Form10
Dim con As New SqlClient.SqlConnection
Dim cmd, com As New SqlClient.SqlCommand
Dim sqlda As New SqlClient.SqlDataAdapter
Dim ds As New DataSet
Private Sub Form10_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
con.ConnectionString = "data source=.\sqlexpress;initial catalog =pharmacy;Integrated Security =true"
Catch ex As Exception
MessageBox.Show(ex.Message, "Connection Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error)
End Try
End Sub
Private Sub btnclear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclear.Click
txtdcode.Text = ""
txtrinvo.Text = ""
txtcreg.Text = ""
txtprice.Text = ""
txtqty.Text = ""
txttamount.Text = ""
DateTimePicker1.Text = ""
End Sub
Private Sub btnsearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsearch.Click
con.Open()
Try
sqlda = New System.Data.SqlClient.SqlDataAdapter("SELECT * FROM return where r_invoice_no='" & txtrinvo.Text & "'", con)
ds.Clear()
sqlda.Fill(ds, "return")
txtdcode.Text = ds.Tables("return").Rows(0).Item(0)
txtcreg.Text = ds.Tables("return").Rows(0).Item(1)
txtprice.Text = ds.Tables("return").Rows(0).Item(2)
txtqty.Text = ds.Tables("return").Rows(0).Item(3)
txttamount.Text = ds.Tables("return").Rows(0).Item(4)
DateTimePicker1.Text = ds.Tables("return").Rows(0).Item(5)
ProgressBar1.Visible = True
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 10000
ProgressBar1.Value = 0
Dim I As Integer
For I = ProgressBar1.Minimum To ProgressBar1.Maximum
ProgressBar1.Value = I
Next
ProgressBar1.Visible = False
Catch ex As IndexOutOfRangeException
MsgBox("Type correct Return Invoice Number to search.." & ex.Message, MsgBoxStyle.Critical, "TRY AGAIN")
Finally
con.Close()
End Try
End Sub
Private Sub btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadd.Click
con.Open()
Try
If txtdcode.Text = "" Or txtrinvo.Text = "" Or txtcreg.Text = "" Or txtprice.Text = "" Or txtqty.Text = "" Or txttamount.Text = "" Or DateTimePicker1.Text = "" Then
MsgBox("You must have to fill all the Book details.")
Else
Dim strInst As String = "INSERT INTO return(drug_code,c_reg_no,Sale_price,qty,Tot_amount,date,r_invoice_no)VALUES('" & txtdcode.Text & "','" & txtcreg.Text & "','" & txtprice.Text & "','" & txtqty.Text & "','" & txttamount.Text & "','" & DateTimePicker1.Text & "','" & txtrinvo.Text & "')"
Dim cmd_Insert As New System.Data.SqlClient.SqlCommand(strInst, con)
cmd_Insert.ExecuteNonQuery()
ProgressBar1.Visible = True
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 10000
ProgressBar1.Value = 0
Dim I As Integer
For I = ProgressBar1.Minimum To ProgressBar1.Maximum
ProgressBar1.Value = I
Next
MsgBox("New Recored has been Added", MsgBoxStyle.Information)
ProgressBar1.Visible = True
txtdcode.Text = ""
txtrinvo.Text = ""
txtcreg.Text = ""
txtprice.Text = ""
txtqty.Text = ""
txttamount.Text = ""
DateTimePicker1.Text = ""
End If
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Error Inserting")
Finally
con.Close()
End Try
End Sub
Private Sub btnupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnupdate.Click
Try
con.Open()
com.Connection = con
com.CommandText = "UPDATE return SET drug_code ='" & txtdcode.Text & "',c_reg_no='" & txtcreg.Text & "',Sale_price='" & txtprice.Text & "',qty='" & txtqty.Text & "',Tot_amount='" & txttamount.Text & "',date='" & DateTimePicker1.Text & "'"
com.ExecuteNonQuery()
ProgressBar1.Visible = True
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 10000
ProgressBar1.Value = 0
Dim I As Integer
For I = ProgressBar1.Minimum To ProgressBar1.Maximum
ProgressBar1.Value = I
Next
MsgBox("Your rocord has been Updated", MsgBoxStyle.Information, "Update Records")
ProgressBar1.Visible = False
txtdcode.Text = ""
txtrinvo.Text = ""
txtcreg.Text = ""
txtprice.Text = ""
txtqty.Text = ""
txttamount.Text = ""
DateTimePicker1.Text = ""
Catch ex As Exception
MessageBox.Show("Error while updating password on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
End Sub
Private Sub btndelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndelete.Click
Try
con.Open()
com.Connection = con
com.CommandText = "Delete From return Where r_invoice_no=" & txtrinvo.Text
com.ExecuteNonQuery()
ProgressBar1.Visible = True
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 10000
ProgressBar1.Value = 0
Dim I As Integer
For I = ProgressBar1.Minimum To ProgressBar1.Maximum
ProgressBar1.Value = I
Next
MsgBox("Records are deleted with Return Invoice Number..." & txtrinvo.Text, MsgBoxStyle.Information, "Record Deleted.")
ProgressBar1.Visible = False
txtdcode.Text = ""
txtrinvo.Text = ""
txtcreg.Text = ""
txtprice.Text = ""
txtqty.Text = ""
txttamount.Text = ""
DateTimePicker1.Text = ""
Catch ex As InvalidCastException
MessageBox.Show("Error while retrieving records on table..." & ex.Message, "Load Records")
Finally
con.Close()
End Try
End Sub
End Class
Change this line:
Dim strInst As String = "INSERT INTO return(drug_code,c_reg_no,Sale_price,qty,Tot_amount,date,r_invoice_no)VALUES('" & txtdcode.Text & "','" & txtcreg.Text & "','" & txtprice.Text & "','" & txtqty.Text & "','" & txttamount.Text & "','" & DateTimePicker1.Text & "','" & txtrinvo.Text & "')"
To this:
Dim strInst As String = "INSERT INTO [return](drug_code,c_reg_no,Sale_price,qty,Tot_amount,date,r_invoice_no)VALUES('" & txtdcode.Text & "','" & txtcreg.Text & "','" & txtprice.Text & "','" & txtqty.Text & "','" & txttamount.Text & "','" & DateTimePicker1.Text & "','" & txtrinvo.Text & "')"
Notice the square brackets around the table name. Return is a reserved word in SQL Server, which is causing your error. I would recommend that you change the name of the table. If this is not possible, then you are stuck adding the square brackets every time you use the table.

Resources