Datagridview and access database only updates after clicking a different row - vb.net

I am reading an access database and populating the info in datagridview. My form has a DGV, and 3 buttons.
Button one copies the selected row to a datetimepicker control.
Button two copied the updated datetimepicker value back to the DVG
Button three does an update (writes the info back to the database).
My issue is that the info only gets updated in the database if I select a different row before hitting button three. I am not getting any error message in either case.
Below is my code. The database only has 2 columns (name and DOB - which is date/time).
Public Class Form1
Dim dbConn As New OleDb.OleDbConnection
Dim sDataset As New DataSet
Dim sDataAdapter As OleDb.OleDbDataAdapter
Dim sql As String
Dim iTotalRows As Integer
Dim sShipTypeFilter As String
Dim sBuildingFilter As String
Dim sCustSuppFilter As String
Dim sStatusFilter As String
Dim sDayFilter As String
Dim dv As New DataView
Sub myDBConn()
dbConn.ConnectionString = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\terry\Documents\Database1.accdb"
Debug.Print("Start:" & DateAndTime.Now.ToString)
dbConn.Open()
sql = "select * from TableX"
sDataAdapter = New OleDb.OleDbDataAdapter(Sql, dbConn)
sDataAdapter.Fill(sDataset, "MyTable")
dbConn.Close()
iTotalRows = sDataset.Tables("MyTable").Rows.Count
Debug.Print("Rows from Access:" & iTotalRows)
Debug.Print("End:" & DateAndTime.Now.ToString)
End Sub
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Call myDBConn()
Debug.Print("DVG1 row count before binding:" & DataGridView1.Rows.Count)
'dv = New DataView(sDataset.Tables(0), "Shipment = 'Regular' and Building = 'CSE'", "Company DESC", DataViewRowState.CurrentRows)
dv = sDataset.Tables(0).DefaultView
Debug.Print("DataView count:" & dv.Count)
DataGridView1.DataSource = dv
Debug.Print("DVG1 Rows:" & DataGridView1.Rows.Count)
DataGridView1.Columns("DOB").DefaultCellStyle.Format = "hh:mm tt"
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
dtp1.Value = DataGridView1.SelectedRows(0).Cells("DOB").Value
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
DataGridView1.SelectedRows(0).Cells("DOB").Value = dtp1.Value
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Debug.Print("switched row")
Me.Visible = False
Dim sqlcb As New OleDb.OleDbCommandBuilder(sDataAdapter)
sDataAdapter.Update(sDataset.Tables("MyTable"))
Me.Close()
End Sub
End Class

Before updating you need to Endedit. This means you need to add Endedit for the datagridview.
So this will be your code:
Debug.Print("switched row")
Me.Visible = False
Dim sqlcb As New OleDb.OleDbCommandBuilder(sDataAdapter)
Datagridview1.EndEdit()
sDataAdapter.Update(sDataset.Tables("MyTable"))
Me.Close()
EDIT1:
Dim dt As New DataTable
dbConn.Open()
sDataset.Tables.Add(dt)
sDataAdapter = New OleDbDataAdapter("Select * from TableX", dbConn)
sDataAdapter.Update(dt)
dbConn.Close()

I figured it out - thanks Stef for putting me on the right track.
My DGV is only updated programmatically (not by user edits) so I updated the code for button 2 to set the editmode, begin editing, update the selected DVG row and end editing:
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
DataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically
DataGridView1.BeginEdit(True)
DataGridView1.SelectedRows(0).Cells("DOB").Value = dtp1.Value
DataGridView1.EndEdit()
End Sub
After doing this modification - my datadapter.update command works!!

Related

ADODB vb.net ComboBox value to Textbox working on the last index only

I'm having a problem here in vb.net where I need to get the value of the combobox value to textbox. but it only shows the last index of the combobox. /
//here is my code
Private Sub cboname_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboname.SelectedIndexChanged
strSql = "SELECT * FROM tblCashier WHERE ProductCode= '" & cboname.Text & "' "
Do Until myRecord.EOF
txtname.Text = myRecord.Fields("Product").Value
myRecord.MoveNext()
Loop
Call executeQuery2(strSql)
Call getRecord()
End Sub
// ADODB CONNECTIONS
Dim strSql As String
Dim myRecord As New ADODB.Recordset
// COMBO BOX VALUES
Sub fillcombo()
strSql = "SELECT * FROM tblCashier"
Do While Not myRecord.EOF
cboname.Items.Add(myRecord.Fields("ProductCode").Value)
myRecord.MoveNext()
Loop
cboname.Refresh()
Call executeQuery(strSql)
Call getRecord()
End Sub
// FORM_LOAD
Private Sub myPOS_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call openConnection()
Call getRecord()
Call fillcombo()
End Sub
This sort of thing should be done something like this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using adapter As New OleDbDataAdapter("SQL query here", "connection string here")
Dim table As New DataTable
adapter.Fill(table)
BindingSource1.DataSource = table
With ComboBox1
.DisplayMember = "ColumnNameToDisplay"
.ValueMember = "PrimaryKeyColumnName"
.DataSource = BindingSource1
End With
TextBox1.DataBindings.Add("Text", BindingSource1, "OtherColumnNameToDisplay")
End Using
End Sub
The TextBox will then automatically update as the selection in the ComboBox changes.

No New Row Entry Added to Access Backend

so I made this code which is supposed to update the Delivery table in my MS Access database. The code runs fine and even says that data entry is successful, but upon checking the database file no new row entry is made.
Public Class NewDelivery
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim con As New OleDb.OleDbConnection
Public Shared stxtboxsupsel As TextBox
Public Shared supnum As String
Public Shared dgvitems As DataGridView
Private Sub NewDelivery_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "MM/dd/yyyy"
End Sub
Private Function OpenDBConnection()
If My.Settings.DatabaseLoc = "" Then
Dim directory As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Return "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & directory & "\IE156.mdb"
Else
Return "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & My.Settings.DatabaseLoc
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
My.Forms.ManageInventory.Show()
Me.Close()
End Sub
Private Sub btnSelSupp_Click(sender As Object, e As EventArgs) Handles btnSelSupp.Click
My.Forms.SelectSupplier.Show()
stxtboxsupsel = txtboxsupsel
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
con.ConnectionString = OpenDBConnection()
con.Open()
Dim sql As String = "INSERT INTO Delivery(ItemPurchDate,SupNum) VALUES (#ItemPurchDate,#SupNum)"
Dim cmd As New OleDb.OleDbCommand(sql, con)
cmd.Parameters.AddWithValue("#ItemPurchDate", DateTimePicker1.Text)
cmd.Parameters.AddWithValue("#SupNum", supnum)
con.Close()
Me.Close()
MsgBox("New Delivery Recorded")
End Sub
The Delivery Table has 3 columns namely ItemPurchNum (Primary Key and Autonumber), ItemPurchDate(date/time) and SupNum(Number and has a many to one relationship with SupNum from my Supplier table).
I had no trouble adding new rows in my other forms following the similar code. Any thoughts on why it won't add a new row? Thank you in advance!
thanks for your help. Noticed that I skipped a line cmd.ExecuteNonQuery(), and now it works!

HOW TO FILL COMBO BOX IN VB.NET

I have a code to fill my combo box but every time i close the form the list is being doubled, if i have a list from my database of English, Mathematics, Science after i close the form and open it again the list showing is now English, Mathematics, Science, English, Mathematics, Science
HERE IS THE CODE,
Call OpenDB()
cmd.CommandText = "select * from Subject"
cmd.Connection = conn
dr = cmd.ExecuteReader
While dr.Read()
cmbSubject.Items.Add(dr("Subject Name"))
End While
dr.Close()
Call CloseDB()
The problem is not in the method you are using to bind the combobox. in each time it binds that's why you are getting duplicate records in the database. to avoid this please clear the combobox before each bind, like the following:
Call OpenDB()
cmbSubject.Items.Clear ' extra statement added to clear the item collection
cmd.CommandText = "select * from Subject"
cmd.Connection = conn
dr = cmd.ExecuteReader
While dr.Read()
cmbSubject.Items.Add(dr("Subject_Name"))
End While
dr.Close()
Call CloseDB()
If you need an alternate method for binding the combobox i will suggest you binding with Dataset
following is the example code for this :
Dim SQL As String= "select Subject_Name,Subject_code from Subject"
Dim adapter As New OdbcDataAdapter(SQL, conn) '<-- This function will Retrieve Data and Return as Dataset together with table name
Dim myData As New DataSet
myData.Fill(lobjDataSet, tblName)
cmbSubject.DataSource = ds_myData
cmbSubject.DataMember = "Subject"
cmbSubject.DataTextField = "Subject_Name"
cmbSubject.DataValueField = "Subject_code"
cmbSubject.DataBind()
myData .Dispose()
Public Class frmRegistration
Dim obj As New Entity.Registration
Dim bus As New Business.Registration
Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
BindingSource1.EndEdit()
bus.Save(obj)
RefreshGrid()
MsgBox("Saved.")
End Sub
Sub RefreshGrid()
Dim dt1 As DataTable = bus.Select()
BindingSource2.DataSource = dt1
DataGridView1.AllowUserToAddRows = False
DataGridView1.DataSource = BindingSource2
End Sub
Private Sub Registration_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
RefreshGrid()
NewItem()
End Sub
Private Sub BtnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnNew.Click
NewItem()
End Sub
Sub ResetDis()
BindingSource1.DataSource = obj
End Sub
Sub NewItem()
obj = New Entity.Registration
ResetDis()
End Sub
Private Sub BindingSource2_CurrentChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BindingSource2.CurrentChanged
obj = New Entity.Registration(CType(Me.BindingSource2.Current, DataRowView).Row)
ResetDis()
End Sub
End Class

Does not taking the update data

I have One Dataset binding in Reportviewer, My dataset Have two Paramters, in Report loud data will displays in normally put the problem is when i pass the paremeters in new values reportviewer and I click search Button the previous data in reportviewer does meat any changes. means the newer searched data will not be displayed!
Here is my Code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
mysession()
ReportViewer1.ProcessingMode = ProcessingMode.Local
Dim rep As LocalReport = ReportViewer1.LocalReport
rep.ReportPath = "Leaving Report.rdlc"
Dim ds1 As DataSet = GetData()
Dim EMpReplt As New ReportDataSource()
EMpReplt.Name = "ProlDataSet_Lrepoert"
EMpReplt.Value = ds1.Tables("EMPData")
rep.DataSources.Add(EMpReplt)
End sub
Private Function GetSalesData()
Dim ds As New DataSet
Dim sql As String = "select * from laeve where Status='" & DropDownList1.SelectedValue & "' and Agent='" & Session("Agence") & "'"
Dim command As New SqlCommand(sql,con)
Dim mysqlAdapter As New SqlDataAdapter(command)
mysqlAdapter.Fill(ds, "EMPData")
mysqlAdapter.Dispose()
command.Dispose()
End Using
Return ds
End Function
End Sub
Protected Sub Search_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click
ReportViewer1.LocalReport.Refresh()
End Sub
Try to place the .IsPostBack Using the WebForms ReportViewer Control
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
mysession()
If Not Page.IsPostBack Then
ReportViewer1.ProcessingMode = ProcessingMode.Local
Dim rep As LocalReport = ReportViewer1.LocalReport
rep.ReportPath = "Leaving Report.rdlc"
Dim ds1 As DataSet = GetData()
Dim EMpReplt As New ReportDataSource()
EMpReplt.Name = "ProlDataSet_Lrepoert"
EMpReplt.Value = ds1.Tables("EMPData")
rep.DataSources.Add(EMpReplt)
End if
End sub

DataGridView and BindingSource timer issue

I have a DataGridview that displays the data and a TextBox that allows me to filter the BindingSource with an SQL query to display the data based on the input string. This is all working fine apart from once I have filtered the DataGridView the timer function I have is resetting it back so all the data is being displayed again. The timer is set on a 1000ms basis, so it will show the filtered result for a second, then revert back.
Heres my code:
Imports System.Data.OleDb
Public Class Form1
Dim duraGadgetDB As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Dave\Documents\duraGadget.mdb;"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sql As String = "SELECT * FROM duragadget"
Dim connection As New OleDbConnection(duraGadgetDB)
Dim dataadapter As New OleDbDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "dura")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "dura"
DataGridView1.Columns(5).Width = 300
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
insert.Show()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim currentRowID As Integer
Dim scrollPosition As Integer = DataGridView1.FirstDisplayedScrollingRowIndex
Try
If DataGridView1.CurrentRow IsNot Nothing Then
currentRowID = DataGridView1.CurrentRow.Index
Dim sql As String = "SELECT * FROM duragadget"
Dim connection As New OleDbConnection(duraGadgetDB)
Dim dataadapter As New OleDbDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "dura")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "dura"
DataGridView1.CurrentCell = DataGridView1.Item(1, currentRowID)
End If
Catch ex As Exception
End Try
DataGridView1.FirstDisplayedScrollingRowIndex = scrollPosition
End Sub
Private Sub txtSearchOnSku_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearchOnSku.TextChanged
Dim currentRowID As Integer
Dim scrollPosition As Integer = DataGridView1.FirstDisplayedScrollingRowIndex
Try
If DataGridView1.CurrentRow IsNot Nothing Then
currentRowID = DataGridView1.CurrentRow.Index
Dim sql As String = "SELECT * FROM duragadget"
Dim connection As New OleDbConnection(duraGadgetDB)
Dim dataadapter As New OleDbDataAdapter(sql, connection)
Dim ds As New DataSet()
Dim dsView As New DataView
Dim bs As New BindingSource()
connection.Open()
dataadapter.Fill(ds, "dura")
connection.Close()
dsView = ds.Tables(0).DefaultView
bs.DataSource = dsView
bs.Filter = "skuNo LIKE'" & txtSearchOnSku.Text & "*'"
DataGridView1.DataSource = bs
DataGridView1.CurrentCell = DataGridView1.Item(1, currentRowID)
End If
Catch ex As Exception
End Try
DataGridView1.FirstDisplayedScrollingRowIndex = scrollPosition
End Sub
End Class
Can anyone tell me how to stop this happening?
Assuming you mean that, if you have entered a value in your text box to filter your results, that you then don't want you timer to fire and unfilter them...
You can either, check the contents of the TextBox in the Timer1_Tick routine;
If txtSearchOnSku.Text <> "" Then Exit Sub
Or you can disable your timer in the txtSearchOnSku_TextChanged routine;
If txtSearchOnSku.Text <> "" Then
Timer1.Stop
Else
Timer1.Start
End If
Or, if you want to update your results once a second, based on you search, you can include the Filtering code in your Timer1_Tick routine.
As a quick point, you have alot of repeated code there. It may be worthwhile refactoring the repeated code out into another sub.