Can some one please assist me? How to get rid of this error?
concurrency violation : Updated 0 of the expected 1 records
I have been struggling with the update command for the last couple of days. I tried many solutions from the internet but I am unable to resolve this issue.
Imports Microsoft.Office
Imports System.Data.OleDb
Public Class Form1
Dim dt As New DataTable
Dim cnn As New OleDb.OleDbConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'filling analyst filter
Dim sText As String = String.Empty
Dim sConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\ecxx-store\Exxx xxxxsk\Txx Axxx\Enxx Flxxx\Source\Exx_Exxx_Flagging.accdb" 'Put your connection string in here
Using cn As New OleDb.OleDbConnection(sConnString)
cn.Open()
Dim cmd As New OleDb.OleDbCommand("SELECT Distinct Analyst FROM EF ORDER BY Analyst", cn)
Dim r As OleDb.OleDbDataReader = cmd.ExecuteReader()
While r.Read()
ComboBox7.Items.Add(r("analyst"))
End While
r.Close()
cn.Close()
End Using
'end of filling analyst filter
Me.EFTableAdapter.Fill(Me.Exx_Exxxx_ShippingDataset.EF)
Me.Label19.Text = "Welcome " & StrConv(Environment.MachineName, vbProperCase)
Me.Label20.Text = EFBindingSource.Count.ToString() & " entries"
'Setting Followup Status
Me.ComboBox8.Text = "Waiting for approval"
'disabling Second Analyst Details
Me.txtsecondanalyst.Enabled = False
Me.txtapproval.Enabled = False
Me.txtnotes.Enabled = False
End Sub
Private Sub txtdof_ValueChanged(sender As Object, e As EventArgs) Handles txtdof.ValueChanged
Me.txtnd.Text = DateDiff(DateInterval.Day, CDate(txtdof.Text), Now())
End Sub
Private Sub ComboBox7_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox7.SelectedIndexChanged
If IsNothing(Me.ComboBox8.Text) Then
EFBindingSource.Filter = "[Analyst] LIKE '%" & ComboBox7.Text & "%'"
Else
EFBindingSource.Filter = "[FollowupStatus] LIKE '%" & ComboBox8.Text & "%' AND [Analyst] Like '%" & ComboBox7.Text & "%'"
End If
'count of datagrid
Me.Label20.Text = EFBindingSource.Count.ToString() & " entries"
End Sub
Private Sub ComboBox8_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox8.SelectedIndexChanged
If IsNothing(Me.ComboBox7.Text) Then
EFBindingSource.Filter = "[FollowupStatus] LIKE '%" & ComboBox8.Text & "%'"
Else
EFBindingSource.Filter = "[FollowupStatus] LIKE '%" & ComboBox8.Text & "%' AND [Analyst] Like '%" & ComboBox7.Text & "%'"
End If
'count of datagrid
Me.Label20.Text = EFBindingSource.Count.ToString() & " entries"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'update
Me.txtnd.Visible = True
Me.txtnd.Text = DateDiff(DateInterval.Day, CDate(txtdof.Text), Now())
On Error GoTo SaveErr
EFBindingSource.EndEdit()
EFTableAdapter.Update(Exx_Exxxx_ShippingDataset.EF)
Me.txtsecondanalyst.Enabled = False
Me.txtapproval.Enabled = False
Me.txtnotes.Enabled = False
MsgBox("Record Updated or Saved")
SaveErr:
End Sub
Private Sub Form1_Closed(sender As Object, e As EventArgs) Handles Me.Closed
EFBindingSource.EndEdit()
Me.TableAdapterManager1.UpdateAll(Me.Exx_Exxx_ShippingDataset)
End Sub
End Class
According to Concurrency violation: the UpdateCommand affected 0 of the expected 1 records. DB concurrencyException was unhandled
You call
Me.EFTableAdapter.Fill(Me.Exx_Exxxx_ShippingDataset.EF)
in Form_Load, but there is no guarantee that the rows aren't changed by the time you call
EFTableAdapter.Update(Exx_Exxxx_ShippingDataset.EF)
in Button1_Click
In the linked answer,
ADO.Net keeps the value of the column when it was selected from the database. When it performs the update the condition is that none of the columns have changed when you commit.
Perhaps you should call
dt = dt.GetChanges()
immediately before updating in Button1_Click, so that the datatable gets updated with the latest values in the database.
Related
Anyone can help me with this please ?
The app you see rn is nothing like the app im working on , i made it way simple.
** because of the versions ?? I'm using VB.net2017 / Ms-AccessDb 2010**
this code below is a simple version that i made , of my main app that im working on , because my main code has too many radio buttons( equipments status to check if they on or fail ) and more than 15 textbox , and i did put them in same Db table as columns that the insert query looks so long in vb , cuz i didnt know any other method , and i dont want create the gridviewcolumns myself because i got over 50 columns that would be long , i just need to use simple code as possible .
the thing is , i keep getting the errors in these lines below :
connection.open() [error said cant find the file , but my file path is not wrong]
mycommand.CommandText = "INSERT INTO Status (.... ect )
mycommand.ExecuteNonQuery() [ error : exception .... ]
da.Fill(ds, "[Status]") [also error in the select query coudnt find the table or incorrect file name ]
pic1(click me): example of error i keep getting
pic2 : the simple form1 with it code below .
pic3 : my Ms-AccessDb
Imports System.Data.OleDb
Public Class Form1
Dim s1 As Boolean
Dim s2 As Boolean
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label_currentdate.Text = DateTime.Now.ToString()
End Sub
Private Sub BTN_Save_Click(sender As Object, e As EventArgs) Handles BTN_Save.Click
Dim myconnexion As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data source=C:\Users\acer\Desktop\ABC.accdb")
Dim mycommand As OleDbCommand = myconnexion.CreateCommand()
myconnexion.Open()
mycommand.CommandText = "INSERT INTO Status (item-Number,CurrentDate,Employee_Name,Equip2 status,Equip1 status)
VALUES('" & Label_items.Text & "','" & Label_currentdate.Text & "','" & TextBox_EmployeeName.Text & "','" & s1 & "','" & s2 & "')"
mycommand.ExecuteNonQuery()
MsgBox(" successfully saved !")
myconnexion.Close()
End Sub
Private Sub RB1_CheckedChanged(sender As Object, e As EventArgs) Handles RB1.CheckedChanged
s1 = True
End Sub
Private Sub RB2_CheckedChanged(sender As Object, e As EventArgs) Handles RB2.CheckedChanged
s1 = False
End Sub
Private Sub RB3_CheckedChanged(sender As Object, e As EventArgs) Handles RB3.CheckedChanged
s2 = True
End Sub
Private Sub RB4_CheckedChanged(sender As Object, e As EventArgs) Handles RB4.CheckedChanged
s2 = False
End Sub
Private Sub BTN_reset_Click(sender As Object, e As EventArgs) Handles BTN_reset.Click
Dim RB As RadioButton
TextBox_EmployeeName.Text = ""
For Each RB In GBX1.Controls
RB.Checked = False
Next
For Each RB In GBX2.Controls
RB.Checked = False
Next
End Sub
Private Sub Label_currentdate_Click(sender As Object, e As EventArgs)
End Sub
Private Sub BTN_History_Click(sender As Object, e As EventArgs) Handles BTN_History.Click
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim table As DataTableCollection
Dim source1 As New BindingSource
'
'
conn = New OleDbConnection With {.ConnectionString = "provider=Microsoft.ACE.OLEDB.12.0;Data source=C:\Users\acer\Desktop\ABC.accdb"}
ds = New DataSet
table = ds.Tables
da = New OleDbDataAdapter("Select * from [Status]", conn)
da.Fill(ds, "[Status]")
Dim view As New DataView(table(0))
source1.DataSource = view
DataGridView.DataSource = view
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Label_items.Text = "item number 1 "
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Label_items.Text = "item number 2"
End Sub
End Class
You can't have spaces in field names, and a date value must be formatted properly. Also, Status may be a reserved word, and - if s1 and s2 are numeric - no quotes:
Label_currentdate.Text = DateTime.Today.ToString("yyyy'/'MM'/'dd")
<snip>
mycommand.CommandText = "INSERT INTO [Status] ([item-Number],CurrentDate,Employee_Name,[Equip2 status],[Equip1 status])
VALUES('" & Label_items.Text & "',#" & Label_currentdate.Text & "#,'" & TextBox_EmployeeName.Text & "'," & s1 & "," & s2 & ")"
But do consider using parameters. Much cleaner and simpler to maintain.
i'm getting an error when i'm trying to update my database
Syntax error in UPDATE statement
item:In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user.
error code: -2147217900
errors: {System.Data.OleDb.OleDbErrorCollection}
Imports System.Data.OleDb
Public Class Ubah_Password
Dim kns As New OleDbConnection("provider=microsoft.ace.oledb.15.0;data source =" & Application.StartupPath & "\database.accdb")
Dim da As New OleDbDataAdapter
Dim ds As New DataSet
Dim sql As String
Sub tampilkan() 'menampilkan semua user
ds.Clear()
sql = "SELECT * FROM USERLIST"
da.SelectCommand = New OleDbCommand(sql, kns)
da.Fill(ds, "USERLIST")
End Sub
Sub cariid() 'mencari id
ds.Clear()
sql = "select * from USERLIST where USERNAME = '" & LOGIN.USERNAME.Text & "'"
da.SelectCommand = New OleDbCommand(sql, kns)
da.Fill(ds, "USERLIST")
End Sub
Sub gantiid() 'mengganti password
sql = "update USERLIST set USERNAME = '" & LOGIN.USERNAME.Text & "', PASSWORD= '" & renew.Text & "' where USERNAME ='" & LOGIN.USERNAME.Text & "'"
kns.Open()
da.UpdateCommand = New OleDbCommand(sql, kns)
da.UpdateCommand.ExecuteNonQuery()
kns.Close()
End Sub
Private Sub Ubah_Password_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
MAIN_MENU.Panel1.Visible = True
End Sub
Private Sub Ubah_Password_Load(sender As Object, e As EventArgs) Handles MyBase.Load
tampilkan()
MAIN_MENU.Panel1.Visible = False
End Sub
Private Sub oldpass_TextChanged(sender As Object, e As EventArgs) Handles oldpass.TextChanged
cariid()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
cariid()
If ds.Tables("USERLIST").Rows.Count = 0 Then
MessageBox.Show("You Have Enter Wrong Password", "Warning!")
oldpass.Clear()
newpass.Clear()
renew.Clear()
oldpass.Focus()
ElseIf ds.Tables("USERLIST").Rows.Count = 1 And newpass.Text <> renew.Text Then
MessageBox.Show("New Password And Confirmation Must Be Same!", "Warning!")
newpass.Clear()
renew.Clear()
newpass.Focus()
ElseIf ds.Tables("USERLIST").Rows.Count = 1 And newpass.Text = renew.Text Then
gantiid()
MessageBox.Show("Password Change Is Successful!", "Notice")
Me.Close()
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
End Class
First I populated the datagridview by data of sqlserver 2008 database table, now i have muliple rows in datagridview containing data, i am trying to update any row but, in the database table it replaces other rows data by the row data that iam trying to update
the code for update statement is given below
Plz help me
Dim cmd As New SqlCommand("Update EmployeeDetail Set Salary = '" &
dgvEmpDetail.Rows(0).Cells(1).Value & "', Experience ='" &
dgvEmpDetail.Rows(0).Cells(2).Value & "', Skills='" &
dgvEmpDetail.Rows(0).Cells(3).Value
& "' where Emp_ID = '" & dgvEmpDetail.Rows(0).Cells(0).Value & "'", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
You've hard coded the row - dgvEmpDetail.Rows(0).
I imagine you are calling this in a loop. You should do something like:
For i As Integer = 0 To dgvEmpDetail.Rows.Count - 1
Dim cmd As New SqlCommand("Update EmployeeDetail Set Salary = '" & dgvEmpDetail.Rows(i).Cells(1).Value & "', Experience ='" & dgvEmpDetail.Rows(i).Cells(2).Value & "', Skills='" & dgvEmpDetail.Rows(i).Cells(3).Value()& "' where Emp_ID = '" & dgvEmpDetail.Rows(i).Cells(0).Value & "'", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Next
Your code is susceptible to SQL injection. You should put the update SQL in to a stored procedure - its faster and safer!
Protected Sub Page_Load()
If Not Page.IsPostBack Then
' Create a new table.
Dim taskTable As New DataTable("TaskList")
' Create the columns.
taskTable.Columns.Add("Id", GetType(Integer))
taskTable.Columns.Add("Description", GetType(String))
taskTable.Columns.Add("IsComplete", GetType(Boolean))
'Add data to the new table.
For i = 0 To 19
Dim tableRow = taskTable.NewRow()
tableRow("Id") = i
tableRow("Description") = "Task " + i.ToString()
tableRow("IsComplete") = False
taskTable.Rows.Add(tableRow)
Next
'Persist the table in the Session object.
Session("TaskTable") = taskTable
'Bind data to the GridView control.
BindData()
End If
End Sub
Protected Sub TaskGridView_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
TaskGridView.PageIndex = e.NewPageIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
'Set the edit index.
TaskGridView.EditIndex = e.NewEditIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowCancelingEdit()
'Reset the edit index.
TaskGridView.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
'Retrieve the table from the session object.
Dim dt = CType(Session("TaskTable"), DataTable)
'Update the values.
Dim row = TaskGridView.Rows(e.RowIndex)
dt.Rows(row.DataItemIndex)("Id") = (CType((row.Cells(1).Controls(0)), TextBox)).Text
dt.Rows(row.DataItemIndex)("Description") = (CType((row.Cells(2).Controls(0)), TextBox)).Text
dt.Rows(row.DataItemIndex)("IsComplete") = (CType((row.Cells(3).Controls(0)), CheckBox)).Checked
'Reset the edit index.
TaskGridView.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Private Sub BindData()
TaskGridView.DataSource = Session("TaskTable")
TaskGridView.DataBind()
End Sub
</script>
I have a access connection with textbox as data feeder to database change it to SQL if u want. The code is:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class Form2
Dim conaccess As New OleDbConnection
Dim conreader As OleDbDataReader
Dim concmd As New OleDbCommand
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.EditMode = False
conaccess.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source=d:\vijay.mdb"
conaccess.Open()
loadGrid()
End Sub
Private Sub loadGrid()
Dim access As String
access = "select * from vijay"
Dim DataTab As New DataTable
Dim DataAdap As New OleDbDataAdapter(access, conaccess)
DataAdap.Fill(DataTab)
DataGridView1.DataSource = DataTab
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
Dim no As String
no = "select Max(ID) from vijay"
Dim concmd As New OleDbCommand(no, conaccess)
conreader = concmd.ExecuteReader
If (conreader.Read) Then
If (IsDBNull(conreader(0))) Then
id_txt.Text = "1"
Else
id_txt.Text = conreader(0) + 1
End If
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End If
End Sub
Private Sub DataGridView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Try
id_txt.Text = DataGridView1.Item(0, i).Value
name_txt.Text = DataGridView1.Item(1, i).Value
class_txt.Text = DataGridView1.Item(2, i).Value
gen_txt.Text = DataGridView1.Item(3, i).Value
branch_txt.Text = DataGridView1.Item(4, i).Value
age_txt.Text = DataGridView1.Item(5, i).Value
Catch ex As Exception
End Try
End Sub
Private Sub del_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles del_btn.Click
Dim delcmd As New OleDbCommand("delete from vijay where id=" & id_txt.Text & " ", conaccess)
delcmd.ExecuteNonQuery()
MsgBox("Record is deleted")
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
Dim access As String = String.Format("INSERT INTO vijay (Name,Class,Branch,Gender,Age) VALUES('{0}','{1}','{2}','{3}','{4}')", name_txt.Text, class_txt.Text, branch_txt.Text, gen_txt.Text, age_txt.Text)
concmd.Connection = conaccess
concmd.CommandText = access
concmd.ExecuteNonQuery()
MsgBox("Record Successfully Saved")
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
Private Sub up_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles up_btn.Click
Dim access As String
access = "UPDATE vijay SET Name = '" & name_txt.Text & "', Age = '" & age_txt.Text & "', Gender ='" & gen_txt.Text & "' , Branch ='" & branch_txt.Text & "' , Class = '" & class_txt.Text & "' where id=" & id_txt.Text & ""
Dim cmd As New OleDbCommand(access, conaccess)
cmd.ExecuteNonQuery()
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
End Class
Use looping and parameter (to handle sql injection):
con.Open() 'Open connection to database
'Looping throung dgv
For i As Integer = 0 To dgvEmpDetail.Rows.Count - 1
If IsDBNull(dgvEmpDetail.Rows(i).Cells("Emp_ID").Value) Then Exit For
Dim cmd As New SqlCommand("Update EmployeeDetail Set [Salary] = ?, [Experience]=?, [Skills]=? WHERE [Emp_ID] =?", con)
With cmd.Parameters
.AddWithValue("#Salary", dgvEmpDetail.Rows(i).Cells("Salary").Value )
.AddWithValue("#Experience", dgvEmpDetail.Rows(i).Cells("Experience").Value )
.AddWithValue("#Skills", dgvEmpDetail.Rows(i).Cells("Skills").Value )
.AddWithValue("#Emp_ID", dgvEmpDetail.Rows(i).Cells("Emp_ID").Value )
End With
cmd.ExecuteNonQuery()
Next i
con.Close() 'Close connection with Database
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.
i am having some issues updating a table that i have in a VB.net Windows Forms in VS 2012
i have setup the database from a service Data base, it just need a small amount of data stored locally
what i am trying to do when i create a new user it update the data grid view
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BDate1.Format = DateTimePickerFormat.Custom
BDate1.CustomFormat = "MM/dd/yyyy"
If fname.Text <> "" And lname.Text <> "" Then
If Not cn.State = ConnectionState.Open Then
cn.Open()
End If
' cn1.Open()
If rb1.Checked Then
gen = rb1.Text.ToString
ElseIf rb2.Checked Then
gen = rb2.Text.ToString
End If
cmd.CommandText = "INSERT INTO StudentTB (FirstName,LastName,Birthday,Avatar,Gender,Grade) values('" & fname.Text & "', '" & lname.Text & "', '" & BDate1.Text & "', '" & AvtarNM.Text & "', '" & gen & "', '" & TxtGrade.Text & "')"
Dim dt As New DataTable
dt.Load(cmd.ExecuteReader())
DataGridView1.DataSource = dt
' cmd.ExecuteNonQuery()
cn.Close()
fname.Text = ""
lname.Text = ""
the issue is that i can clear the table and reload it with button but it does not show the updated values with out closing the application then reopening it, i have tried a few thing and nothing seems to refresh the connection and or update the database. any help would help.
thanks
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
'DataGridView1.DataSource = Nothing
Database1DataSet1.StudentTB.Clear()
' Database1DataSet1.refresh()
' Dim myda As String
' cmd.Dispose()
' cmd.Connection = cn
'Me.Database1DataSet1.Clear()
Me.StudentTBTableAdapter.Fill(Me.Database1DataSet1.StudentTB)
' 'myda = New SqlDataAdapter(cmd)
End Sub
here is the full code
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlClient.SqlDataReader
Imports System.Windows.Forms
Public Class Student
Dim cn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Nate\documents\visual studio 2012\Projects\WindowsApplication9\WindowsApplication9\Database1.mdf;Integrated Security=True")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Private dataAdapter As New SqlDataAdapter()
Dim gen As String
Dim bs As New BindingSource
Dim dt As New DataTable
Private Sub Student_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database1DataSet1.avTable' table. You can move, or remove it, as needed.
Me.AvTableTableAdapter.Fill(Me.Database1DataSet1.avTable)
'TODO: This line of code loads data into the 'Database1DataSet1.StudentTB' table. You can move, or remove it, as needed.
Me.StudentTBTableAdapter.Fill(Me.Database1DataSet1.StudentTB)
cmd.Connection = cn
Form1.Hide()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If AvTableBindingSource.Position + 1 < AvTableBindingSource.Count Then
AvTableBindingSource.MoveNext()
Button7.PerformClick()
' Otherwise, move back to the first item.
Else
AvTableBindingSource.MoveFirst()
Button7.PerformClick()
End If
' Force the form to repaint.
Me.Invalidate()
End Sub
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
PictureBox1.Image = System.Drawing.Bitmap.FromFile(ID.Text)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BDate1.Format = DateTimePickerFormat.Custom
BDate1.CustomFormat = "MM/dd/yyyy"
If fname.Text <> "" And lname.Text <> "" Then
If Not cn.State = ConnectionState.Open Then
cn.Open()
End If
' cn1.Open()
If rb1.Checked Then
gen = rb1.Text.ToString
ElseIf rb2.Checked Then
gen = rb2.Text.ToString
End If
cmd.CommandText = "INSERT INTO StudentTB (FirstName,LastName,Birthday,Avatar,Gender,Grade) values('" & fname.Text & "', '" & lname.Text & "', '" & BDate1.Text & "', '" & AvtarNM.Text & "', '" & gen & "', '" & TxtGrade.Text & "')"
cmd.ExecuteNonQuery()
dt.Load(cmd.ExecuteReader())
bs.DataSource = dt
DataGridView1.DataSource = bs
cn.Close()
fname.Text = ""
lname.Text = ""
End If
End Sub
Private Sub genPCI()
If rb1.Checked Then
gen = rb1.Text.ToString
ElseIf rb2.Checked Then
gen = rb2.Text.ToString
End If
End Sub
Public Function ChangeFormat(ByVal dtm As DateTime, ByVal format As String) As String
Return dtm.ToString(format)
End Function
Private Sub Closestudent_Click(sender As Object, e As EventArgs) Handles Closestudent.Click
Form1.Show()
Me.Close()
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
bs.EndEdit()
dataAdapter.Update(dt)
DataGridView1.DataSource = dt
' dt.Load(Command.ExecuteReader())
'Database1DataSet1.Reset()
'DataGridView1.Columns.Clear()
' DataGridView1.DataSource = Nothing
' Me.StudentTBTableAdapter.Fill(Me.Database1DataSet1.StudentTB)
' StudentTBBindingSource.ResetBindings(True)
' Database1DataSet1.refresh()
' Dim myda As String
' cmd.Dispose()
' cmd.Connection = cn
' StudentTBBindingSource.ResetBindings(False)
'Database1DataSet1.StudentTB.Clear()
' 'myda = New SqlDataAdapter(cmd)
' DataGridView1.DataSource = Database1DataSet1.StudentTB
End Sub
End Class
You can try like this
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
bs.EndEdit()
dataadapter.Update(dt)
DataGridView1.DataSource = dt
End Sub
UPDATE
or you can use bindingdatasource and delare it on your form class
Dim bs As New BindingSource
and in datagridview .. in button1_click
Dim dt As New DataTable
dt.Load(cmd.ExecuteReader())
bs.DataSource = dt
DataGridView1.DataSource = bs
So, if updated then will show after button4_click
Datagridview1.datasource = nothing
Dataset.reset
dim cmd as new sqldataadapter
cmd = "SELECT * FROM YOUR_DATABSE", con
con.open
cmd.fill(Dataset)
datagridview1.datasource = dataset(0).defaultview
Add these code to you button insert
okay after a lot of playing around this seem to fix my issue http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx well all i can say it is working no idea why but it works.
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Me.DataGridView1.DataSource = Me.StudentTBBindingSource
GetData("select * from StudentTB")
End Sub
Private Sub GetData(ByVal selectCommand As String)
Try
' Specify a connection string. Replace the given value with a
' valid connection string for a Northwind SQL Server sample
' database accessible to your system.
Dim connectionString As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Nate\documents\visual studio 2012\Projects\WindowsApplication9\WindowsApplication9\Database1.mdf;Integrated Security=True"
' Create a new data adapter based on the specified query.
Me.dataAdapter = New SqlDataAdapter(selectCommand, connectionString)
' Create a command builder to generate SQL update, insert, and
' delete commands based on selectCommand. These are used to
' update the database.
Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapter)
' Populate a new data table and bind it to the BindingSource.
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.StudentTBBindingSource.DataSource = table
' Resize the DataGridView columns to fit the newly loaded content.
' Me.DataGridView1.AutoResizeColumns( _
' DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)
Catch ex As SqlException
MessageBox.Show("To run this example, replace the value of the " + _
"connectionString variable with a connection string that is " + _
"valid for your system.")
End Try
End Sub
By Using ComboBox To Search
sql = " select * from english_language where lang=' " & ComboBox2.Text & " ' "
da = New OleDb.OleDbDataAdapter(sql, con)
Dim dt As New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
DataGridView1.Refresh()
Try this code to btnClear.
DataGridView.DataSource = 0
Press clear button. After that click the reload button that you coded.
I think it will reset and reload the data in data grid view.