Data updation and deletion error - vb.net

I have a DataGrid and many text fields to add data into the database. When i add a new data, it gets updated in the database and in the data grid.But when i delete the data, it gets deleted only from the database. It doesn't get updated in the data grid.
When i try to update the data, it updates only one record at a time.when i try for another record it gives me a error "The variable name '#date' has already been declared. Variable names must be unique within a query batch or stored procedure." I have to close and reopen the form to update a new record.
Imports System.Data.SqlClient
Public Class Form
Dim con As New SqlClient.SqlConnection("Server = DEL-PC; Database=Shj; Trusted_Connection=yes;")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim ds As DataSet
Dim da As SqlDataAdapter
Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SqlDataAdapter1.Fill(DataSet11)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles newbtn.Click
If RegNoTextBox.Text <> "" Then
cmd.Connection = con
con.Open()
cmd.CommandText = "insert into WaterProofing(Date,RegNo) values ('" & DateDateTimePicker.Value & "','" & RegNoTextBox.Text & "')"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
Else
MessageBox.Show("Please enter registration number")
End If
End Sub
//updation
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles editbtn.Click
cmd.Parameters.AddWithValue("#date", DateDateTimePicker.Value)
cmd.Parameters.AddWithValue("#regno", RegNoTextBox.Text)
cmd.Connection = con
con.Open()
cmd.CommandText = "update WaterProofing set RegNo= #regno where date=#date"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
MessageBox.Show("Details Updated!")
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletebtn.Click
cmd.Connection = con
con.Open()
cmd.CommandText = "delete from WaterProofing where date='" & DateDateTimePicker.Value & "'"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
MessageBox.Show("Details Deleted!")
End Sub
Sub showdata()
SqlDataAdapter1.Fill(DataSet11, "WaterProofing")
With DataGridView
.Update()
End With
End Sub
End Class
Please help me in deletion and updating.

You're adding parameters before declaring CommandText at Button2_Click
Try it in this way:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles editbtn.Click
Try
Dim command As New SqlCommand
con.Open()
command.Connection = con
command.CommandText = "update WaterProofing set RegNo= #regno where date=#date"
command.Parameters.AddWithValue("#date", DateDateTimePicker.Value)
command.Parameters.AddWithValue("#regno", RegNoTextBox.Text)
command.ExecuteNonQuery()
con.Close()
Call showdata()
MessageBox.Show("Details Updated!")
Catch ex as Exception
MessageBox.Show(ex.Message)
End try
End Sub
UPDATE
Basically you have to do the same thing when you load the DataGridView for the first time in order to refresh the DataGridView with the current data from database after deleting or updating records, so your ShowData Sub might look something like this
Private Sub ShowData()
Dim Connection As SqlConnection
Connection = New SqlConnection("YourConnectionString")
Try
Connection.Open()
Dim SQL As String = "SELECT Field1, Field2, Field3 FROM Table"
Dim DS As New DataSet
Dim Adapter As New SqlDataAdapter(SQL, Connection)
Adapter.Fill(DS)
DataGridView.DataSource = DS.Tables(0)
DataGridView.Refresh()
Catch ex As Exception
MessageBox(ex.Message)
Finally
Connection.Close()
End Try
End Sub

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletebtn.Click
Try
Dim command As New SqlCommand
con.Open()
command.Connection = con
command.CommandText = "delete from WaterProofing where date='" & DateDateTimePicker.Value & "'"
command.ExecuteNonQuery()
con.Close()
Call ShowData_Delete()
MessageBox.Show("Details Deleted!")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
End Try
End Sub
Private Sub ShowData_Delete()
Dim Connection As SqlConnection
Try
Connection = New SqlConnection("Server = DEL-PC; Database=Shj; Trusted_Connection=yes;")
Connection.Open()
Dim SQL As String = "SELECT * from WaterProofing"
Dim DS As New DataSet
Dim Adapter As New SqlDataAdapter(SQL, Connection)
Adapter.Fill(DS)
DataGridView1.DataSource = DS.Tables(0)
DataGridView1.Refresh()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Connection.Close()
End Try
End Sub

Related

DataGridView refreshing fixed position in row filter textbox in vb.net

I want when filtering rows in the textbox then the database is updated from other applications then I do a refresh I want the datagridview that I filter in the textbox in a fixed position and also when selected in the combobox as well. Maybe my code isn't perfect. So there may be the best solution.
Thanks
VIEW DATAGRIDVIEW
Public Class Form1
Dim Path As String = Application.StartupPath()
Dim cn = "provider=Microsoft.Jet.OLEDB.4.0; data source=" & Path & "; Extended Properties=dBase IV"
Private WithEvents dt As New DataTable
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.PopulateComboBox()
Me.PopulateDataGridView()
Me.clearfiltercombobox()
End Sub
Private Sub PopulateDataGridView()
Try
Dim query = "select ITM,ART,QTY FROM EXAMPLE WHERE QTY > 0 AND BRAND = #BRAND"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#BRAND", ComboBox1.SelectedValue)
Using adapter As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
adapter.Fill(dt)
Me.DataGridView1.DataSource = dt
End Using
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Try
CType(DataGridView1.DataSource, DataTable).DefaultView.RowFilter = String.Format("ITM LIKE '%{0}%' OR ITM LIKE '%{0}%'", TextBox1.Text)
Catch ex As Exception
MsgBox("No match found")
End Try
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectionChangeCommitted
Me.TextBox1.Text = ""
Me.PopulateDataGridView()
End Sub
Private Sub PopulateComboBox()
Dim query As String = "SELECT DISTINCT BRAND FROM EXAMPLE WHERE QTY > 0"
Try
Using con As OleDbConnection = New OleDbConnection(cn)
Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con)
'Fill the DataTable with records from Table.
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
'Insert the Default Item to DataTable.
Dim row As DataRow = dt.NewRow()
row(0) = ""
dt.Rows.InsertAt(row, 0)
'Assign DataTable as DataSource.
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "BRAND"
ComboBox1.ValueMember = "BRAND"
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub clearfiltercombobox()
Try
ComboBox1.ResetText()
TextBox1.Text = ""
Dim query = "select ITM,ART,QTY FROM EXAMPLE WHERE QTY > 0"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
Using adapter As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
adapter.Fill(dt)
Me.DataGridView1.DataSource = dt
End Using
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub Refreshonly_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Refreshonly.Click
Me.clearfiltercombobox()
DataGridView1.Refresh()
End Sub
Private Sub clearall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Clearall.Click
Me.clearfiltercombobox()
End Sub
End Class

Adapter update statement in oledb

I have a form with retrieved data form ms access database. While updating using the adapter update statement, it shows Syntax error.
The following are the connection code in form load event and update button click event.
could you please let me know whats wrong in this?
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Dim Con As New OleDbConnection()
Dim Cmd As New OleDbCommand
Dim SQL As String = "SELECT * FROM Heidelberg"
Con.ConnectionString = strConn
Try
Con.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Cmd = New OleDbCommand(SQL, Con)
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
ds = New DataSet
Adapter.Fill(ds, "testing")
MaxRows = ds.Tables("testing").Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
Dim cb As New OleDb.OleDbCommandBuilder(Adapter)
ds.Tables("testing").Rows(inc).Item(5) = TextBox1.Text
ds.Tables("testing").Rows(inc).Item(2) = TextBox2.Text
ds.Tables("testing").Rows(inc).Item(3) = TextBox3.Text
ds.Tables("testing").Rows(inc).Item(4) = TextBox4.Text
Try
Adapter.Update(ds, "testing")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
You have way too many commands in your Form.Load.
One
Dim Cmd As New OleDbCommand
Two
Cmd = New OleDbCommand(SQL, Con)
Three
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
Every time you use the New keyword, you create another command.
If you are only dealing with a single table, you don't need a DataSet. The extra object adds extra weight and complicates the code a bit.
Private inc As Integer
Private Adapter As New OleDbDataAdapter
Private MaxRows As Integer
Private dat As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Using Con As New OleDbConnection(strConn)
Using Cmd As New OleDbCommand("SELECT * FROM Heidelberg;", Con)
Adapter.SelectCommand = Cmd
Try
Adapter.Fill(dat)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Using
MaxRows = dat.Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
dat.Rows(inc).Item(5) = TextBox1.Text
dat.Rows(inc).Item(2) = TextBox2.Text
dat.Rows(inc).Item(3) = TextBox3.Text
dat.Rows(inc).Item(4) = TextBox4.Text
Dim cb As New OleDbCommandBuilder(Adapter)
'This will take care of any spaces that you have in column names.
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Try
Adapter.Update(dat)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

refresh button for datagridview

i need help in refresh the datagridview. I create a Update button and show button but it didn't refresh. but i check in my database access it update successful
Imports System.Data
Imports System.Data.OleDb
Public Class Form2
Public con As OleDbConnection
Public da As OleDbDataAdapter
Public ds As New DataSet
Public cmd As OleDbCommand
Public dr As OleDbDataReader
Dim count As Integer = 100
Dim ID As String
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
'Establish connection
con = New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\m_j_g\Documents\Visual Studio 2010\Projects\DatabaseApplication\Department.accdb")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShow.Click
Try
'establish connection
con = New OleDbConnection("provider = Microsoft.ACE.OLEDB.12.0; data source = C:\Users\m_j_g\OneDrive\Documents\Database1.accdb")
'execute sql query
da = New OleDbDataAdapter("Select * from table1", con)
'Fill Dataset
da.Fill(ds, "table1")
'put data from dataset to datagridview
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUpdate.Click
con = New OleDbConnection("provider = Microsoft.ACE.OLEDB.12.0; data source = C:\Users\m_j_g\OneDrive\Documents\Database1.accdb")
Try
con.Open()
cmd = New OleDbCommand("Update table1 set SurName='" & TextBox2.Text & "', FirstName='" & TextBox3.Text & "' where EmailAddress='" & TextBox5.Text & "'", con)
'Execute UPDATE Query
cmd.ExecuteNonQuery()
MsgBox("Record Updated Successfully..." & Chr(13) & "Email Address: " & TextBox5.Text & Chr(13) & "SurName: " & TextBox2.Text & Chr(13) & "FirstName: " & TextBox3.Text)
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I am newbie in programming Thank you for your help
You need to rebind the Grid after performing the update, Follow these steps this may help you:
Define a Method for binding the giridiew, this will populate the grid with values from the DB:
Public Sub bindMyGrid()
con = New OleDbConnection("provider = Microsoft.ACE.OLEDB.12.0; data source = C:\Users\m_j_g\OneDrive\Documents\Database1.accdb")
da = New OleDbDataAdapter("Select * from table1", con)
da.Fill(ds, "table1")
DataGridView1.Rows.Clear() '<-- new line added
DataGridView1.DataSource = ds.Tables(0)
End Sub
Call the method in the click event of the show button to populate the grid:
Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShow.Click
Try
bindMyGrid()
Catch ex As Exception
' handle error here
End Try
End Sub
Perform the update operation on update button click, and call the method again to get the latest values.
Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUpdate.Click
Try
'Perform the update operations here
' Call bindMyGrid() to rebind the grid
bindMyGrid() 'this will populate the new value to the grid.
Catch ex As Exception
'Handle error here
End Try
End Sub

“syntax error in INSERT INTO statement”

I'm a beginner in vb.net
I've got the following Error upon executing the Insert-Statement
syntax error in INSERT INTO statement
Here is my code:
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(?,?,?)"
Dim cmd As New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("?", txtid)
.Parameters.AddWithValue("?", txtuser)
.Parameters.AddWithValue("?", txtpass)
.ExecuteNonQuery()
End With
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Could anyone help me?
Try to use sql parameter names
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(#ID,#Username,#Password)"
Dim cmd As New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("#ID", txtid)
.Parameters.AddWithValue("#Username", txtuser)
.Parameters.AddWithValue("#Password", txtpass)
.Open()
.ExecuteNonQuery()
.Close()
End With
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Note that: You should properly close your connections after you use them. Therefore following code may be better.
Private Sub InsertLogin()
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(#ID,#Username,#Password)"
Using con As New OleDbConnection(ConnectionStringHERE)
Using cmd As New OleDbCommand
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#ID", txtid)
cmd.Parameters.AddWithValue("#Username", txtuser)
cmd.Parameters.AddWithValue("#Password", txtpass)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
InsertLogin()
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Here, I used cmd. syntax, it is no different then using With.
You have to name the sql parameters.
Look at the examples in the documentation: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue%28v=vs.110%29.aspx

using CheckedListBox in vb.net2008

In vb.net 2008, How To insert Multiple selected Data from Checkedlistbox to Database sql server 2005?
My Code is
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Cn.Close()
Cn.Open()
Try
cmd.CommandText = "insert into Module_Control_tbl (empl_ID,Module_ID) Values('" & ComboBox1.SelectedValue & "','" & CheckedListBox1.SelectedValue & "')"
ComboBox1.Focus()
cmd.Connection = Cn
cmd.ExecuteNonQuery()
MsgBox("Assign Module Successfully to Employee")
Form7_Load(sender, e)
Catch ex As Exception
MsgBox(ex.Message)
MsgBox("contact to Your System Administrator")
End Try
Cn.Close()
You should just iterate through the CheckedItems collection.
Furthermore, you should always use parameters to avoid SQL injection.
Here is an example:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using cn As New SqlConnection("Connection String")
cn.Open()
Dim sb As New StringBuilder
sb.AppendLine("INSERT INTO Module_Control_tbl")
sb.AppendLine("(empl_ID, Module_ID)")
sb.AppendLine("VALUES")
sb.AppendLine("(#empl_ID, #module_ID)")
For Each item In CheckedListBox1.CheckedItems
Using cmd As New SqlCommand(sb.ToString, cn)
cmd.Parameters.AddWithValue("#empl_ID", ComboBox1.SelectedValue.ToString)
cmd.Parameters.AddWithValue("#module_ID", item.ToString)
cmd.ExecuteNonQuery()
End Using
Next
End Using
End Sub