Update a database record - vb.net

I use following code to update database record after retrieving data to the text boxes via a datagridview.
But this gives me an exception as object reference not set to an instance of the object. Please help
Private Sub DataGridView_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridViewUserType.CellClick
Dim i As Integer
i = DataGridViewUserType.CurrentRow.Index
If i >= 0 Then
Me.txtBoxID.Text = DataGridViewUserType.Item(0, i).Value
Me.txtBoxUserType.Text = DataGridViewUserType.Item(1, i).Value
Else
MessageBox.Show("Empty Row Clicked")
End If
End Sub
Private Sub btnUserTypeUpdate_Click(sender As Object, e As EventArgs) Handles btnUserTypeUpdate.Click
Try
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE dbo.User_Type SET Type = #tp WHERE Type_ID = #ID"
cmd.Parameters.AddWithValue("#ID", txtBoxID.Text)
cmd.Parameters.AddWithValue("#tp", txtBoxUserType.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Successfully Updated")
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Update Records")
Finally
con.Close()
btnUserTypeSave.Show()
txtBoxID.Clear()
txtBoxUserType.Clear()
End Try
End Sub

Thankz Fabio
The error was with "cmd"
I just put Dim cmd As SqlCommand = New SqlCommand before using it and now it is functioning.
Thankz All

Related

how to update and insert in one button in dapper with database MS Access in VB.NET

how to update and insert in one button in dapper with database MS Access in VB.NET.
When double click datagridview then the button text changes to edit but the problem is that when the update appears a new record should not appear. The "Contactid" is the autonumber and primarykey type data in the access database and another one I want to ask if the "ContactId" is text and primary type data how to treat the code below?.
if I comment the if statement code and Sql "Insert into" and just run sql "update" status messagebox successfully but the database does not change. I'm using dapper version 1.50.2
Private contactId As Integer = 0
Private Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
If Not Me.btnSave.IsHandleCreated Then Return
Try
If oledbCon.State = ConnectionState.Closed Then
oledbCon.Open()
End If
Dim param As New DynamicParameters()
param.Add("#Nme", txtName.Text.Trim())
param.Add("#Mobile", txtMobile.Text.Trim())
param.Add("#Address", txtAddress.Text.Trim())
param.Add("#ContactID", contactId)
If contactId = 0 Then
oledbCon.Execute("INSERT INTO Contact (Nme,Mobile,Address) VALUES (#Nme,#Mobile,#Address)", param, commandType:=CommandType.Text)
MessageBox.Show("Saved Successfully")
Else
oledbCon.Execute("UPDATE Contact SET Nme = #Nme,Mobile = #Mobile,Address = #Address WHERE ContactID = #ContactID", param, commandType:=CommandType.Text)
MessageBox.Show("Updated Successfully")
End If
FillDataGridView()
Clear()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
oledbCon.Close()
End Try
End Sub
Private Sub dgvContact_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles dgvContact.DoubleClick
If Not Me.dgvContact.IsHandleCreated Then Return
Try
If dgvContact.CurrentRow.Index <> -1 Then
'contactId = Convert.ToInt32(dgvContact.CurrentRow.Cells(0).Value.ToString())
txtName.Text = dgvContact.CurrentRow.Cells(1).Value.ToString()
txtMobile.Text = dgvContact.CurrentRow.Cells(2).Value.ToString()
txtAddress.Text = dgvContact.CurrentRow.Cells(3).Value.ToString()
btnDelete.Enabled = True
btnSave.Text = "Edit"
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Sub
'I created one update button to test sql for update running or not but the code below has an error "Data type mismatch in criteria expression"
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
If Not Me.btnUpdate.IsHandleCreated Then Return
Try
Using oledbCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\DapperCRUD.accdb")
If oledbCon.State = ConnectionState.Closed Then
oledbCon.Open()
End If
Dim param As New DynamicParameters()
param.Add("#Nme", txtName.Text.Trim())
param.Add("#Mobile", txtMobile.Text.Trim())
param.Add("#Address", txtAddress.Text.Trim())
param.Add("#ContactID", txtcontactid.Text.Trim())
oledbCon.Execute("UPDATE Contact SET Nme = '" & txtName.Text & "',Mobile = '" & txtMobile.Text & "',Address = '" & txtAddress.Text & "' WHERE ContactID = '" & txtcontactid.Text & "'", param, commandType:=CommandType.Text)
MessageBox.Show("Updated Successfully")
FillDataGridView()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
oledbCon.Close()
End Try
End Sub
database access datatype
as per the answer from #ZoHas link!
Private Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
If Not Me.btnSave.IsHandleCreated Then Return
Try
If oledbCon.State = ConnectionState.Closed Then
oledbCon.Open()
End If
Dim param As New DynamicParameters()
param.Add("#Nme", txtName.Text.Trim())
param.Add("#Mobile", txtMobile.Text.Trim())
param.Add("#Address", txtAddress.Text.Trim())
param.Add("#ContactID", txtcontactid.Text)
If String.IsNullOrEmpty(Me.txtcontactid.Text.Trim()) Then
oledbCon.Execute("INSERT INTO Contact (Nme,Mobile,Address) VALUES (#Nme,#Mobile,#Address)", param, commandType:=CommandType.Text)
MessageBox.Show("Saved Successfully")
Else
oledbCon.Execute("UPDATE Contact set Nme=#param1, Mobile=#param2, Address=#param3 where ContactID=#param4", New With {
Key .param1 = txtName.Text.Trim(),
Key .param2 = txtMobile.Text.Trim(),
Key .param3 = txtAddress.Text.Trim(),
Key .param4 = txtcontactid.Text}, commandType:=CommandType.Text)
MessageBox.Show("Updated Successfully")
End If
FillDataGridView()
Clear()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
oledbCon.Close()
End Try
End Sub

VB.NET SQL Database locked

My data table is loaded in 2 places, a DataGridView and a ComboBox
The ComboBox is to select a record to edit (a TextBox to enter a new value)
And the DataGridView is to see the changes (I gave up (for now) updating directly from the DataGridView)
Private Sub EditLoc_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
con.Open()
Dim sql = Nothing
sql = "SELECT Location FROM Location"
Dim cmdDataGrid As SQLiteCommand = New SQLiteCommand(sql, con)
Dim da As New SQLiteDataAdapter
da.SelectCommand = cmdDataGrid
Dim dt As New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
Dim readerDataGrid As SQLiteDataReader = cmdDataGrid.ExecuteReader()
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Try ' TRY CATCH for combobox
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT Location FROM Location"
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBox1.Items.Add(dr.GetString(0))
Loop
If ComboBox1.Items.Count > 0 Then
ComboBox1.SelectedIndex = 0 ' The first item has index 0 '
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
This works perfectly
Picture
The problem is when I click Save, the app hangs a while, and then I get the "Database is locked" error picture
Here is the code for the Save button:
Private Sub Savebtn_Click(sender As Object, e As EventArgs) Handles Savebtn.Click
Try
con.Open()
cmd = con.CreateCommand
cmd.CommandText = "UPDATE Location set Location = '" & TextBox1.Text & "' WHERE Location = '" & ComboBox1.Text & "'"
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Thanks for the help
I fixed this problem by removing all "cmd.Dispose()", "da.Dispose()" and "con.Close()" from the code, leaving them ONLY in
Private Sub Closebtn_Click(sender As Object, e As EventArgs) Handles Closebtn.Click
da.Dispose()
cmd.Dispose()
con.Close()
Dim fems As New EMS
fems.Show()
Me.Close()
End Sub
On Form Load I have
Private Sub EditLoc_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.Open()
Call pull()
End Sub
And the Pull sub has all the rest...
Private Sub pull()
Try
Dim sql = Nothing
sql = "SELECT Location FROM Location"
Dim cmdDataGrid As SQLiteCommand = New SQLiteCommand(sql, con)
da.SelectCommand = cmdDataGrid
Dim dt As New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
Dim readerDataGrid As SQLiteDataReader = cmdDataGrid.ExecuteReader()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Try ' TRY CATCH for combobox
cmd.Connection = con
cmd.CommandText = "SELECT Location FROM Location"
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBox1.Items.Add(dr.GetString(0))
Loop
If ComboBox1.Items.Count > 0 Then
ComboBox1.SelectedIndex = 0 ' The first item has index 0 '
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
And here is my Save button
Private Sub Savebtn_Click(sender As Object, e As EventArgs) Handles Savebtn.Click
If Not TextBox1.Text = Nothing Then
Try
cmd = con.CreateCommand
cmd.CommandText = "UPDATE Location set Location = '" & TextBox1.Text & "' WHERE Location = '" & ComboBox1.Text & "'"
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Call pull()
TextBox1.Text = Nothing
End If
End Sub
Now everything is working, no errors!
Calling pull() after saving will update the DataGridView
Thanks for the help

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

Data updation and deletion error

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