OleDbAdapter errors, Hides variable in an enclosing block error - vb.net

I've run into some issues/errors regarding some of my OleDb commands. They are shown in the image below:
My goal of the project is to import information (in this case, text) into an Access Database (named Database1) based on which checkboxes are checked. From there the data will be counted based on a couple of different factors, and then used by a coordinating Visual Studio project to display the data in graphs.
I would only like records to be added, not deleted.
I have a feeling that I am missing something very small; maybe just using the wrong value type or inserting the wrong variables. I apologize for the code being very amateur; after all I am new to the programming/ coding world. I'm just not sure how to start fixing these errors.
Here is the whole section of code for reference, if needed:
Private Sub InputInformation(sender As System.Object, e As System.EventArgs) Handles ImporttBUT.Click
Dim con As New OleDb.OleDbConnection(My.Settings.Database1ConnectionString)
con.Open()
MsgBox("OPEN")
Dim builder As New OleDbConnectionStringBuilder With {.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = "S:\software\Melton System\DPD & DEL (KPI)\Database1.accdb",
.PersistSecurityInfo = False}
Dim cmdSQL As SqlCommand = New SqlCommand
Using cmdSQL As New OleDbCommand{"SELECT * from [DataCollection] WHERE ID = 0",
New OleDbConnection(My.Settings.Database1ConnectionString)}
End Using
Dim dt As New DataTable
Dim usertables As DataTable = Nothing
Dim da As OleDb.OleDbDataAdapter(con)
Dim cb As OleDbCommandBuilder
cb = New OleDbCommandBuilder(da)
da.Fill(dt)
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=Database1.accdb; Persist Security Info=False;"
Dim myrow As DataRow = dt.Rows.Add
With dt.Rows.Add
.Item("M/Y Of LOG") = Me.MonthList2021.SelectedItem
.Item("TIME OF LOG") = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")
.Item("USER") = UserName
'' ADD STK ITEM HERE ONCE AUTOFILL IS COMPLETE
If MissedPartCHKB.Checked = True Then
.Item("MISSED PART") = MissedPartCHKB.Text
ElseIf MissedPartCHKB.Checked = False Then
.Item("MISSED PART") = "NEATOL"
End If
If NotInEpicorCHKB.Checked = True Then
.Item("NOT IN EPICOR") = NotInEpicorCHKB.Text
ElseIf NotInEpicorCHKB.Checked = False Then
.Item("NOT IN EPICOR") = "NEATOL"
End If
If MissedBuyoutCHKB.Checked = True Then
.Item("MISSED BUYOUT") = MissedBuyoutCHKB.Text
ElseIf MissedBuyoutCHKB.Checked = False Then
.Item("MISSED BUYOUT") = "NEATOL"
End If
If NonStockCHKB.Checked = True Then
.Item("MISSED NON STOCK ITEM") = NonStockCHKB.Text
ElseIf NonStockCHKB.Checked = False Then
.Item("MISSED NON STOCK ITEM") = "NEATOL"
End If
If MissedSTKItemCHKB.Checked = True Then
.Item("MISSED STOCK ITEM") = MissedSTKItemCHKB.Text
ElseIf MissedSTKItemCHKB.Checked = False Then
.Item("MISSED STOCK ITEM") = "NEATOL"
End If
If MissedAutomatedPartCHKB.Checked = True Then
.Item("MISSED AUTOMATED") = MissedAutomatedPartCHKB.Text
ElseIf MissedAutomatedPartCHKB.Checked = False Then
.Item("MISSED AUTOMATED") = "NEATOL"
End If
If MissingPrintAfterQTYCHKB.Checked = True Then
.Item("MISSING PRINTS AFTER QUANTITY") = MissingPrintAfterQTYCHKB.Text
ElseIf MissingPrintAfterQTYCHKB.Checked = False Then
.Item("MISSING PRINTS AFTER QUANTITY") = "NEATOL"
End If
If MissedPrintsNOTSentChadCHKB.Checked = True Then
.Item("MISSED PRINT NOT SENT TO CHAD") = MissedPrintsNOTSentChadCHKB.Text
ElseIf MissedPrintsNOTSentChadCHKB.Checked = False Then
.Item("MISSED PRINT NOT SENT TO CHAD") = "NEATOL"
End If
If OtherCHKB.Checked = True Then
.Item("OTHER") = OtherTXTB.Text
ElseIf OtherCHKB.Checked = False Then
.Item("OTHER") = "NEATOL"
End If
If AddedMissingDimCHKB.Checked = True Then
.Item("ADDED MISSING DIMENSION") = AddedMissingDimCHKB.Text
ElseIf AddedMissingDimCHKB.Checked = False Then
.Item("ADDED MISSING DIMENSION") = "NEATOL"
End If
If FixedDimensionCHKB.Checked = True Then
.Item("FIXED DIMENSION") = FixedDimensionCHKB.Text
ElseIf FixedDimensionCHKB.Checked = False Then
.Item("FIXED DIMENSION") = "NEATOL"
End If
End With
da.update(dt)
con.Close()
MsgBox("CLOSED")
MissedPartCHKB.Checked = False
MissedAutomatedPartCHKB.Checked = False
NotInEpicorCHKB.Checked = False
NonStockCHKB.Checked = False
MissedSTKItemCHKB.Checked = False
MissedBuyoutCHKB.Checked = False
MissedPrintsNOTSentChadCHKB.Checked = False
MissingPrintAfterQTYCHKB.Checked = False
AddedMissingDimCHKB.Checked = False
FixedDimensionCHKB.Checked = False
OtherCHKB.Checked = False
OtherTXTB.Text = ""
' eventually change the month list to automatically select based on the current date
MonthList2021.SelectedItem = False
End Sub
Here is a preview of my access database:

The most important database object to have in a Using block is a connection.
If the expression you are evaluating in an If statement returns a Boolean, like the Checked property of a check box, you don't need the = True. Since the value of this property can only be True or False, you do not need to recheck it with an ElseIf. An Else will do.
I certainly hope that Time Log field is a Date.
In the Insert statement, the field names with spaces and/or reserved words need to be in brackets [ ]. Access ignores the names of the parameters. We use them to make the code readable. For Access the order that the parameters appear in the sql statement must match the order which they are added to the parameters collection.
Instead of retrieving data you don't use in the Select query and hitting the database twice, once with the .Fill and once with .Update, we will just do the insert of the new record directly. If you do have occasion to use a DataAdapter, it will Open and Close the connection for you if it finds the connection closed. However, if it finds it Open it will leave it Open.
Notice that the connection is not opened until directly before the .Execute... and is closed and disposed with the End Using along with the command.
I moved the resetting of the controls to a separate Sub. Try to keep your methods doing only one thing. Although .SelectedItem takes any Object, False will not do what you expect.
Private Sub InputInformation(sender As System.Object, e As System.EventArgs) Handles ImporttBUT.Click
Dim strSql = "Insert Into [Data Collection] (
[M/Y Of LOG],
[TIME OF LOG],
[USER],
[MISSED PART],
[NOT IN EPICOR],
[MISSED BUYOUT],
[MISSED NON STOCK ITEM],
[MISSED STOCK ITEM],
[MISSED AUTOMATED],
[MISSING PRINTS AFTER QUANTITY],
[MISSED PRINT NOT SENT TO CHAD],
OTHER,
[ADDED MISSING DIMENSION],
[FIXED DIMENSION]
)
Values (#MYLog,#TimeLog, #User, #MissedPart, #NotEpicor, MissedBuyout, #MissedNonStock, #MissedStock,#MissedAutomated, #MissedPrints, #NotSent, #Other, #MissingDimension, #FixedDimension);
"
Using con As New OleDb.OleDbConnection(My.Settings.Database1ConnectionString),
cmdSQL As New OleDbCommand(strSql, con)
With cmdSQL.Parameters
.Add("#MYLog", OleDbType.Date, 100).Value = CDate(MonthList2021.SelectedItem.ToString)
.Add("#TimeLog", OleDbType.Date, 100).Value = DateTime.Now
.Add("#User", OleDbType.VarChar, 100).Value = UserName
.Add("#MissedPart", OleDbType.VarChar, 100)
If MissedPartCHKB.Checked Then
cmdSQL.Parameters("#MissedPart").Value = MissedPartCHKB.Text
Else
cmdSQL.Parameters("#MissedPart").Value = "NEATOL"
End If
.Add("#NotEpicor", OleDbType.VarChar, 100)
If NotInEpicorCHKB.Checked Then
cmdSQL.Parameters("#NotEpicor").Value = NotInEpicorCHKB.Text
Else
cmdSQL.Parameters("#NotEpicor").Value = "NEATOL"
End If
.Add("#MissedBuyout", OleDbType.VarChar, 100)
If MissedBuyoutCHKB.Checked = True Then
cmdSQL.Parameters("#MissedBuyout").Value = MissedBuyoutCHKB.Text
Else
cmdSQL.Parameters("#MissedBuyout").Value = "NEATOL"
End If
.Add("#MissedNonStock", OleDbType.VarChar, 100)
If NonStockCHKB.Checked = True Then
cmdSQL.Parameters("#MissedNonStock").Value = NonStockCHKB.Text
Else
cmdSQL.Parameters("#MissedNonStock").Value = "NEATOL"
End If
.Add("#MissedStock", OleDbType.VarChar, 100)
If MissedSTKItemCHKB.Checked = True Then
.cmdSQL.Parameters("#MissedStock").Value = MissedSTKItemCHKB.Text
Else
cmdSQL.Parameters("#MissedStock").Value = "NEATOL"
End If
.Add("#MissedAutomated", OleDbType.VarChar, 100)
If MissedAutomatedPartCHKB.Checked = True Then
cmdSQL.Parameters("#MissedAutomated").Value = MissedAutomatedPartCHKB.Text
Else
cmdSQL.Parameters("#MissedAutomated").Value = "NEATOL"
End If
.Add("#MissedPrints", OleDbType.VarChar, 100)
If MissingPrintAfterQTYCHKB.Checked = True Then
cmdSQL.Parameters("#MissedPrints").Value = MissingPrintAfterQTYCHKB.Text
Else
cmdSQL.Parameters("#MissedPrints").Value = "NEATOL"
End If
.Add("#NotSent", OleDbType.VarChar, 100)
If MissedPrintsNOTSentChadCHKB.Checked = True Then
cmdSQL.Parameters("#NotSent").Value = MissedPrintsNOTSentChadCHKB.Text
Else
cmdSQL.Parameters("#NotSent").Value = "NEATOL"
End If
.Add("#Other", OleDbType.VarChar, 100)
If OtherCHKB.Checked = True Then
cmdSQL.Parameters("#Other").Value = OtherTXTB.Text
Else
cmdSQL.Parameters("#Other").Value = "NEATOL"
End If
.Add("#MissingDimension", OleDbType.VarChar, 100)
If AddedMissingDimCHKB.Checked = True Then
cmdSQL.Parameters("#MissingDimension").Value = AddedMissingDimCHKB.Text
Else
cmdSQL.Parameters("#MissingDimension").Value = "NEATOL"
End If
.Add("#FixedDimension", OleDbType.VarChar, 100)
If FixedDimensionCHKB.Checked = True Then
cmdSQL.Parameters("#FixedDimension").Value = FixedDimensionCHKB.Text
Else
cmdSQL.Parameters("#FixedDimension").Value = "NEATOL"
End If
End With
con.Open()
cmdSQL.ExecuteNonQuery()
End Using
ResetControls()
End Sub
Private Sub ResetControls()
Dim lstChkBx As New List(Of CheckBox) From {MissedPartCHKB, MissedAutomatedPartCHKB, NotInEpicorCHKB, NonStockCHKB, MissedSTKItemCHKB, MissedBuyoutCHKB, MissedPrintsNOTSentChadCHKB, MissingPrintAfterQTYCHKB, AddedMissingDimCHKB, FixedDimensionCHKB, OtherCHKB}
For Each chk As CheckBox In lstChkBx
chk.Checked = False
Next
OtherTXTB.Text = ""
' eventually change the month list to automatically select based on the current date
'If this is a ListBox
MonthList2021.SelectedIndex = -1
End Sub
Preview of my Access Database:

Related

How to use checkbox for 2 queries for population from DataGridView in vb.net

How to use checkbox for 2 queries for population from DataGridView in vb.net?.
I tried with the code below the population in the datagridview became empty please recommend because maybe my code implementation has something wrong.
Private Sub PopulateDataGridView()
Try
dt = New DataTable
If CheckBox1.Checked = False Then
Dim query = "select ITM,ITC,QOH,PRS,PRSOBBRT,PRSOBNET,SHI,FILENAME1,FILENAME2,FILENAME3,FILENAME4,FILENAME5,FILENAME6,SUBFOLDERP FROM IFG WHERE QOH > 0 AND GDN = 'A.04.01.002.001'"
Else
If CheckBox1.Checked = True Then
Dim query = "select ITM,ITC,QOH,PRS,PRSOBBRT,PRSOBNET,SHI,FILENAME1,FILENAME2,FILENAME3,FILENAME4,FILENAME5,FILENAME6,SUBFOLDERP FROM IFG WHERE QOH < 0 AND GDN = 'A.04.01.002.001'"
Using adapter As New OleDbDataAdapter(query, cn.ToString)
adapter.Fill(dt)
End Using
Me.GridControl1.DataSource = dt
Me.GridControl1.Refresh()
GridView1.Columns("SUBFOLDERP").Visible = False
GridView1.Columns("FILENAME1").Visible = False
GridView1.Columns("FILENAME2").Visible = False
GridView1.Columns("FILENAME3").Visible = False
GridView1.Columns("FILENAME4").Visible = False
GridView1.Columns("FILENAME5").Visible = False
GridView1.Columns("FILENAME6").Visible = False
End If
End If
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
I'm not entirely sure what you're trying to achieve.
You can try something like this:
Dim query As String
If CheckBox1.Checked Then
query = "first query"
Else
query = "second query"
End If
'execute query
Private Sub PopulateDataGridView()
Try
dt = New DataTable
dim query as string = ""
If CheckBox1.Checked Then
query = "select ITM,ITC,QOH,PRS,PRSOBBRT,PRSOBNET,SHI,FILENAME1,FILENAME2,FILENAME3,FILENAME4,FILENAME5,FILENAME6,SUBFOLDERP FROM IFG WHERE QOH < 0 AND GDN = 'A.04.01.002.001'"
Else
Dim query = "select ITM,ITC,QOH,PRS,PRSOBBRT,PRSOBNET,SHI,FILENAME1,FILENAME2,FILENAME3,FILENAME4,FILENAME5,FILENAME6,SUBFOLDERP FROM IFG WHERE QOH > 0 AND GDN = 'A.04.01.002.001'"
End If
Using adapter As New OleDbDataAdapter(query, cn.ToString)
adapter.Fill(dt)
End Using
Me.GridControl1.DataSource = dt
Me.GridControl1.Refresh()
'If these columns should be hidden based on the value of the checkbox, you can just use the value of the checkbox. This is a great way to reduce code provided your condition is SIMPLE
GridView1.Columns("SUBFOLDERP").Visible = CheckBox1.Checked
GridView1.Columns("FILENAME1").Visible = Not Checkbox1.Checked
GridView1.Columns("FILENAME2").Visible = False
GridView1.Columns("FILENAME3").Visible = False
GridView1.Columns("FILENAME4").Visible = False
GridView1.Columns("FILENAME5").Visible = False
GridView1.Columns("FILENAME6").Visible = False
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub

How to Add New Records to An Access Database from Visual Studio. (VB.NET)

Disclaimer: I'm very new into programming, so my coding skills are subpar at best.
My goal is to have my Visual Studio 2019 project (named Detailing Error Log) add a new record row into my Microsoft Access Database table (accdb file named Database1, table named Data Collection) based on which checkboxes are checked. I would only like rows to be added, not deleted, whenever the "Import" button is clicked. The Database will then be saved and the checkboxes in my Visual Studio project unchecked. The Database will be used to store that data until it is used by a coordinating visual studio program to count the occurrences of specific text within a specific month. From there it will be displayed in graphs.
I had successfully accomplished this using Excel, however when the file became too large it caused a great deal of lag; both whenever I ran the debugger and also when refreshing the graphs. I understand there will most likely be a noticeable loading time, but I would like it to be minimized.
My problem is that I am getting this error at my con.Open(): "System.InvalidOperationException: 'The 'Microsoft.ACE.OLEDB.12.0Data Source = S:\software\System\DPD & DEL (KPI)\Database1.accdb' provider is not registered on the local machine."
What does this error mean? This is also currently the only error thrown.
Here is my code for reference, thanks in advance for the help!
*NEATOL = "No Entry At Time Of Log"
Private Sub ConnectionPrep(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim dbProvider As String
Dim dbSource As String
Dim sql As String
Dim inc As Integer
Dim MaxRows As Integer
Dim con As New OleDb.OleDbConnection
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0"
dbSource = "Data Source = S:\software\Melton System\DPD & DEL (KPI)\Database1.accdb; Persist Security Info = False"
con.ConnectionString = dbProvider & dbSource
con.Open()
End Sub
Private Sub InputInformation(sender As System.Object, e As System.EventArgs) Handles ImporttBUT.Click
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim cb As New OleDbCommandBuilder()
Dim dsnewrow As DataRow
dsnewrow = ds.Tables("Data Collection").NewRow()
dsnewrow.Item("M/Y OF LOG") = Me.MonthList2021.SelectedItem
dsnewrow.Item("TIME OF LOG") = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")
dsnewrow.Item("USER") = UserName
dsnewrow.Item("STOCK NUMBER") = Me.StockNumberTXTB.Text
If MissedPartCHKB.Checked = True Then
dsnewrow.Item("MISSED PART") = Me.MissedPartCHKB.Text
ElseIf MissedPartCHKB.Checked = False Then
dsnewrow.Item("MISSED PART") = "NEATOL"
End If
If NotInEpicorCHKB.Checked = True Then
dsnewrow.Item("NOT IN EPICOR") = Me.NotInEpicorCHKB.Text
ElseIf NotInEpicorCHKB.Checked = False Then
dsnewrow.Item("NOT IN EPICOR") = "NEATOL"
End If
If MissedBuyoutCHKB.Checked = True Then
dsnewrow.Item("MISSED BUYOUT") = Me.MissedBuyoutCHKB.Text
ElseIf MissedBuyoutCHKB.Checked = False Then
dsnewrow.Item("MISSED BUYOUT") = "NEATOL"
End If
If NonStockCHKB.Checked = True Then
dsnewrow.Item("MISSED NON STOCK ITEM") = Me.NonStockCHKB.Text
ElseIf NonStockCHKB.Checked = False Then
dsnewrow.Item("MISSED NON STOCK ITEM") = "NEATOL"
End If
If MissedSTKItemCHKB.Checked = True Then
dsnewrow.Item("MISSED STOCK ITEM") = Me.MissedSTKItemCHKB.Text
ElseIf MissedSTKItemCHKB.Checked = False Then
dsnewrow.Item("MISSED STOCK ITEM") = "NEATOL"
End If
If MissedAutomatedPartCHKB.Checked = True Then
dsnewrow.Item("MISSED AUTOMATED") = Me.MissedAutomatedPartCHKB.Text
ElseIf MissedAutomatedPartCHKB.Checked = False Then
dsnewrow.Item("MISSED AUTOMATED") = "NEATOL"
End If
If MissingPrintAfterQTYCHKB.Checked = True Then
dsnewrow.Item("MISSING PRINTS AFTER QUANTITY") = Me.MissingPrintAfterQTYCHKB.Text
ElseIf MissingPrintAfterQTYCHKB.Checked = False Then
dsnewrow.Item("MISSING PRINTS AFTER QUANTITY") = "NEATOL"
End If
If MissedPrintsNOTSentChadCHKB.Checked = True Then
dsnewrow.Item("MISSED PRINT NOT SENT TO CHAD") = Me.MissedPrintsNOTSentChadCHKB.Text
ElseIf MissedPrintsNOTSentChadCHKB.Checked = False Then
dsnewrow.Item("MISSED PRINT NOT SENT TO CHAD") = "NEATOL"
End If
If OtherCHKB.Checked = True Then
dsnewrow.Item("OTHER") = Me.OtherTXTB.Text
ElseIf OtherCHKB.Checked = False Then
dsnewrow.Item("OTHER") = "NEATOL"
End If
If AddedMissingDimCHKB.Checked = True Then
dsnewrow.Item("ADDED MISSING DIMENSION") = Me.AddedMissingDimCHKB.Text
ElseIf AddedMissingDimCHKB.Checked = False Then
dsnewrow.Item("ADDED MISSING DIMENSION") = "NEATOL"
End If
If FixedDimensionCHKB.Checked = True Then
dsnewrow.Item("FIXED DIMENSION") = Me.FixedDimensionCHKB.Text
ElseIf FixedDimensionCHKB.Checked = False Then
dsnewrow.Item("FIXED DIMENSION") = "NEATOL"
End If
ds.Tables("Counting").Rows.Add(dsnewrow)
da.Update(ds, "Counting")
MsgBox("Entry succesfully added to database.")
MissedPartCHKB.Checked = False
MissedAutomatedPartCHKB.Checked = False
NotInEpicorCHKB.Checked = False
NonStockCHKB.Checked = False
MissedSTKItemCHKB.Checked = False
MissedBuyoutCHKB.Checked = False
MissedPrintsNOTSentChadCHKB.Checked = False
MissingPrintAfterQTYCHKB.Checked = False
AddedMissingDimCHKB.Checked = False
FixedDimensionCHKB.Checked = False
OtherCHKB.Checked = False
OtherTXTB.Text = ""
End Sub
It might seem like a good idea to build your connection string that way but it's not. If you want to break it up then do so properly:
Dim builder As New OleDbConnectionStringBuilder
builder.Provider = "Microsoft.ACE.OLEDB.12.0"
builder.DataSource = "S:\software\Melton System\DPD & DEL (KPI)\Database1.accdb"
builder.PersistSecurityInfo = False
Using connection As New OleDbConnection(builder.ConnectionString)
'...
End Using
Doing it properly, you can't forget bits and pieces because there are no bits and pieces. You just supply the values. You also won't end up putting the PersistSecurityInfo value into a variable named dbSource when it's nothing to do with the data source. Pretending to separate your connection string components but not actually doing it properly is worse than not doing it at all.
You can also simplify the code above somewhat like so:
Dim builder As New OleDbConnectionStringBuilder
With builder
.Provider = "Microsoft.ACE.OLEDB.12.0"
.DataSource = "S:\software\Melton System\DPD & DEL (KPI)\Database1.accdb"
.PersistSecurityInfo = False
End With
or, taking it a step further:
Dim builder As New OleDbConnectionStringBuilder With {.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = "S:\software\Melton System\DPD & DEL (KPI)\Database1.accdb",
.PersistSecurityInfo = False}
Try this having the correct semicolons:
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source=S:\software\Melton System\DPD & DEL (KPI)\Database1.accdb; Persist Security Info=False"
con.ConnectionString = dbProvider & dbSource
Source: https://www.connectionstrings.com/access-2013/

index was out of range. must be non-negative and less than the size of the collection. parameter name : index

i got this problem when I want to update data in my sql from datagridview2 that already fill with doubleclickcell from datagridview1
this is the save button code
Try
'reader.Dispose()
Dim iReturn As Boolean
Dim conn As New MySqlConnection("server=localhost;user id=root;password=admin;database=dni")
For i As Integer = 0 To DataGridView2.Rows.Count - 1 Step +1
Using command As New MySqlCommand()
With command
.CommandText = "INSERT INTO dni.tbl_treatmen (`id_treatmen`, `nama_treatmen`, `harga_treatmen`, `Nama_obat`, `qty`, `satuan`) values (#id,#nama,#harga,#namaobat1,#qtyobat1,#satuanobat1) ON DUPLICATE KEY UPDATE
`id_treatmen` = #id,
`nama_treatmen`= #nama,
`harga_treatmen` = #harga,
`Nama_obat`= #namaobat1,
`qty`= #qtyobat1,
`satuan`= #satuanobat1"
.Connection = conn
.CommandType = CommandType.Text
.Parameters.AddWithValue("#id", textbox_id.Text)
.Parameters.AddWithValue("#nama", textbox_nama.Text)
.Parameters.AddWithValue("#harga", textbox_hargajual.Text)
.Parameters.AddWithValue("#namaobat1", DataGridView2.Rows(i).Cells(0).Value.ToString)
.Parameters.AddWithValue("#qtyobat1", DataGridView2.Rows(i).Cells(1).Value.ToString)
.Parameters.AddWithValue("#satuanobat1", DataGridView2.Rows(i).Cells(2).Value.ToString)
End With
Try
conn.Open()
command.ExecuteNonQuery()
iReturn = True
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
iReturn = False
Finally
conn.Dispose()
DataGridView2.DataSource = Nothing
End Try
End Using
Next
MessageBox.Show("Data Saved", "Save Data", MessageBoxButtons.OK, MessageBoxIcon.Information)
textbox_id.Text = "ID Treatmen"
textbox_nama.Text = "Nama Treatmen"
textbox_hargajual.Text = "Harga Jual"
textbox_id.Enabled = False
textbox_nama.Enabled = False
textbox_hargajual.Enabled = False
DataGridView1.Enabled = False
Label2.Visible = False
ShowData()
Button1.Enabled = True
Button2.Enabled = True
Button3.Enabled = False
Button4.Enabled = True
Button5.Enabled = False
Button6.Enabled = False
If aa = 1 Then
DataGridView2.Rows.Clear()
DataGridView2.Columns.Clear()
GroupBox1.Visible = False
ElseIf aa = 2 Then
DataGridView2.DataSource = Nothing
Button9.Visible = False
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
this is the code when i double click cell
Button9.Visible = True
Dim conn = New MySqlConnection
conn.ConnectionString = "server=localhost;userid=root;password=admin;database=dni"
Dim SDA As New MySqlDataAdapter
Dim dbDataSet As New DataTable
Dim bSource As New BindingSource
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow
row = Me.DataGridView1.Rows(e.RowIndex)
textbox_id.Text = row.Cells("ID Treatmen").Value.ToString
textbox_nama.Text = row.Cells("Nama Treatmen").Value.ToString
textbox_hargajual.Text = row.Cells("Harga Treatmen").Value.ToString
Try
conn.Open()
Dim query As String
query = "select nama_obat as 'Nama Obat' , qty as 'Quantity' ,Satuan as 'Satuan' from dni.tbl_treatmen where id_treatmen = #idtreat"
Dim command As New MySqlCommand(query, conn)
SDA.SelectCommand = command
command.Parameters.AddWithValue("#idtreat", textbox_id.Text)
SDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
DataGridView2.DataSource = dbDataSet
SDA.Update(dbDataSet)
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
textbox_id.Enabled = False
textbox_nama.Enabled = True
textbox_hargajual.Enabled = True
Button1.Enabled = False
Button2.Enabled = False
Button3.Enabled = True
Button4.Enabled = True
Button5.Enabled = True
Button6.Enabled = True
End If
this is my code, i want it whenever the datagridview2 is change and i press the save button it will update the record in mysql database.
i use id_treatmen and nama_obat as primary key
Please highlight the exact line of your code where your program is crashing on...
I suspect that you are DESTROYING the DataGrid2 object whilst it is in the middle of the loop
So at the end of the FIRST iteration of your loop you are destroying the DataGrid2 Object and therefore the INDEX is out range.
See the line
DataGridView2.DataSource = Nothing
Which is inside your Try, Catch in the FINALLY Section.

Select N records statement not returning correct amount

I am using a sql statement to connect to an access db and retrieve only 100 records. However, this is returning ALL records and not 100. How do I limit the records I want to fetch. If I run this statement in access directly as a query, it works fine.
I am using winforms in vb.Net.Thanks
sql = "Select top 100 * from Requests ORDER BY [Date-time received] DESC"
vb.Net code
Dim lvcount As Integer = 0
'Dim tmpColor As Color = Color.Green
Sub fillRequests()
Try
DBConnection.connect()
sql = "Select top 100 * from Requests ORDER BY [Date-time received] DESC"
Debug.Print(sql)
Dim oledbCmd As OleDbCommand = New OleDbCommand(sql, oledbCnn)
Using dr = oledbCmd.ExecuteReader()
While dr.Read()
If dr.HasRows Then
Dim LVI As New ListViewItem
With LVI
.UseItemStyleForSubItems = False
.Text = dr(0).ToString()
.SubItems.Add(CDate(dr(5)).ToShortDateString)
.SubItems.Add(dr(1).ToString())
.SubItems.Add(dr(3).ToString())
If dr(3).ToString = "D" Then
.SubItems(3).Text = "Destruction"
ElseIf dr(3).ToString = "O" Then
.SubItems(3).Text = "Retrieval"
ElseIf dr(3).ToString = "I" Then
.SubItems(3).Text = "Intake"
ElseIf dr(3).ToString = "B" Then
.SubItems(3).Text = "Return"
ElseIf dr(3).ToString = "X" Then
.SubItems(3).Text = "Other"
ElseIf dr(3).ToString = "1" Then
.SubItems(3).Text = "Supply std boxes"
ElseIf dr(3).ToString = "G" Then
.SubItems(3).Text = "File Return"
ElseIf dr(3).ToString = "F" Then
.SubItems(3).Text = "File Retrieval"
ElseIf dr(3).ToString = "2" Then
.SubItems(3).Text = "Supply prt boxes"
End If
.SubItems.Add(dr(9).ToString())
If IsDBNull(dr(9)) Then
.SubItems(4).Text = "O/S"
.SubItems(4).ForeColor = Color.Red
'MessageBox.Show(.SubItems(4).Text)
ElseIf dr(9) IsNot "DEMO" Then
.SubItems(4).Text = "Done"
End If
End With
lvRequests.Items.Add(LVI)
lvcount += 1
End If
End While
End Using
'autosize each column in listview
For Each col As ColumnHeader In lvRequests.Columns
col.Width = -2
Next col
'refresh the list with new data
'lvRequests.Refresh()
'Enable the posting previous button
btnPreviousPostings.Enabled = False
btnPreviousPostings.Text = "No data to show"
oledbCnn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
'dr.Close()
'oledbCnn.Close()
End Try
'btnNextPostings.Enabled = ListView1.Items.Count > 100
If (lvRequests.Items.Count < 100) Then
btnNextPostings.Enabled = False
btnNextPostings.Text = "No data to show"
Else
btnNextPostings.Enabled = True
btnNextPostings.Text = "Next " & CStr(lvRequests.Items.Count - 1) & " Postings"
End If
'RESET LVCOUNT TO 0
lvcount = 0
End Sub
From office.microsoft.access.help
The TOP predicate does not choose between equal values.
So if all your records have same value in [Date-time received], then query return all rows.
Workaround:
If you have for example ID-field(or some another field, but with unique values) in your table Requests then use it in ORDER
SELECT TOP 100 * FROM Requests ORDER BY [Date-time received] DESC, [ID] DESC
Just a workaround: If it is not huge data you can get the result into some collection and then get the top 100 items from that collection(I suppose it would be easy using vb.NET) and dispose others off.

da.update command vb.net duplicates data

I have two sections of code. The first one updates data in an access database table called tbl_Customers. It works fine:
Private Sub UpdateRecord()
Dim imgLocation As String
imgLocation = idPictureBox.ImageLocation
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("tbl_Customers").Rows(inc).Item(1) = txtFirstName.Text
ds.Tables("tbl_Customers").Rows(inc).Item(2) = txtSurname.Text
ds.Tables("tbl_Customers").Rows(inc).Item(3) = imgLocation
ds.Tables("tbl_Customers").Rows(inc).Item(4) = mtxtPhoneNumber.Text
ds.Tables("tbl_Customers").Rows(inc).Item(5) = cbReferred.Text
ds.Tables("tbl_Customers").Rows(inc).Item(6) = custType
da.Update(ds, "tbl_Customers")
MessageBox.Show("Data updated", "Update")
btnCommit.Enabled = False
btnClear.Enabled = False
btnAddNew.Enabled = True
btnupdate.Enabled = True
btnDelete.Enabled = True
btnFirst.Enabled = True
btnLast.Enabled = True
btnNext.Enabled = True
btnPrevious.Enabled = True
btnFind.Enabled = True
End Sub
The second piece of code updates an access database table called tbl_SalesInventory. This piece of code duplicates every record in the table!
Private Sub UpdateItemRecord()
Dim cb As New OleDb.OleDbCommandBuilder(da10)
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(1) = txtItemDescription.Text
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(2) = txtItemMin.Text
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(3) = txtItemAsk.Text
Dim SelectedType As Integer = cbSellItemType.SelectedIndex
Dim Type As Integer = SelectedType + 1
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(4) = Type.ToString("D2")
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(5) = txtItemCost.Text
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(6) = dtpItemPDate.Value
If lblItemStatusDisplay.Text = "For Sale" Then
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(7) = "F"
ElseIf lblItemStatus.Text = "On Layaway" Then
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(7) = "L"
ElseIf lblItemStatus.Text = "Sold" Then
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(7) = "S"
ElseIf lblItemStatus.Text = "Displayed" Then
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(7) = "D"
ElseIf lblItemStatus.Text = "Scrapped" Then
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(7) = "X"
End If
Try
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(8) = txtDiaMin.Text
Catch ex As Exception
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(8) = ""
End Try
Try
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(9) = txtDiaValue.Text
Catch ex As Exception
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(9) = ""
End Try
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(10) = txtItemWeight.Text
ds10.Tables("tbl_SalesInventory").Rows(incInv).Item(11) = lblItemMeasure.Text
da10.Update(ds10, "tbl_SalesInventory")
MessageBox.Show("Data updated", "Update")
RefreshDataset()
SortDS10()
btnCommitItem.Enabled = False
btnClearItem.Enabled = False
btnAddItem.Enabled = True
btnUpdateItem.Enabled = True
btnDeleteItem.Enabled = True
btnFirstItem.Enabled = True
btnLastItem.Enabled = True
btnNextItem.Enabled = True
btnPreviousItem.Enabled = True
btnSearchItem.Enabled = True
End Sub
Can anyone shed some light as to why this is happening? Thank you for your prompt response to this issue.