da.update command vb.net duplicates data - vb.net

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.

Related

How to stop the program if the IF statement is true in VB?

So is there any way to stop executing or resuming the program if an IF statement is true? I mean for the program to not resuming the rest of the codes?
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim name As String = ""
Dim phoneNum As String = ""
Dim dblCpu As Double
Dim dblRam As Double
Dim dblMotherboard As Double
Dim dblStorage As Double
Dim dblGpu As Double
Dim dblPcCase As Double
Dim dblPsu As Double
Dim price As Double
Dim tax As Double
Dim total As Double
Const service As Double = 150
input(name, phoneNum, dblCpu, dblRam, dblMotherboard, dblStorage, dblGpu, dblPcCase, dblPsu)
price = calculatePrice(dblCpu, dblRam, dblMotherboard, dblStorage, dblGpu, dblPcCase, dblPsu)
tax = calculateTax(price)
total = calculateTotal(price, tax, service)
output(price, service, tax, total)
End Sub
Sub input(ByRef name As String, ByRef phoneNum As String, ByRef dblCpu As Double, ByRef dblRam As Double,
ByRef dblMotherboard As Double, ByRef dblStorage As Double, ByRef dblGpu As Double,
ByRef dblPcCase As Double, ByRef dblPsu As Double)
name = txtCustName.Text
phoneNum = txtPhoneNum.Text
If radI3.Checked = True Then
dblCpu = 489
ElseIf radI5.Checked = True Then
dblCpu = 859
ElseIf radI7.Checked = True Then
dblCpu = 1399
ElseIf radRyzen3.Checked = True Then
dblCpu = 499
ElseIf radRyzen5.Checked = True Then
dblCpu = 849
ElseIf radRyzen7.Checked = True Then
dblCpu = 1489
End If
//a few other if statements
If (radI3.Checked = True Or radI5.Checked = True Or radI7.Checked = True) And (radAmdAsrock.Checked = True Or radAmdGigabyte.Checked = True) Then
MessageBox.Show("You must select a motherboard that is compatible with the CPU.")
Return
End If
If (radRyzen3.Checked = True Or radRyzen5.Checked = True Or radRyzen7.Checked = True) And (radIntelAsus.Checked = True Or radIntelMsi.Checked = True) Then
MessageBox.Show("You must select a motherboard that is compatible with the CPU.")
Return
End If
If radI3.Checked = False And radI5.Checked = False And radI7.Checked = False And radRyzen3.Checked = False And radRyzen5.Checked = False And radRyzen7.Checked = False Then
MsgBox("You must at least select a CPU.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Alert")
Return
End If
If radIntelAsus.Checked = False And radIntelMsi.Checked = False And radAmdAsrock.Checked = False And radAmdGigabyte.Checked = False Then
MsgBox("You must at least select a motherboard.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Alert")
Return
End If
If radRam8gb.Checked = False And radRam16gb.Checked = False And radRam32gb.Checked = False Then
MsgBox("You must at least select a RAM.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Alert")
Return
End If
If chk120ssd.Checked = False And chk240ssd.Checked = False And chk480ssd.Checked = False And chk1tbssd.Checked = False And chk1tbhdd.Checked = False And chk2tbhdd.Checked = False Then
MsgBox("You must at least select a storage.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Alert")
Return
End If
If radGpu650.Checked = False And radGpu1050ti.Checked = False And radGpu1660ti.Checked = False Then
MsgBox("You must at least select a GPU.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Alert")
Return
End If
If radCaseTecware.Checked = False And radCaseSegotep.Checked = False And radCaseGamdias.Checked = False And radCaseLianLi.Checked = False And radCaseNzxt.Checked = False Then
MsgBox("You must at least select a case.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Alert")
Return
End If
If radpsu450.Checked = False And radpsu550.Checked = False And radpsu650.Checked = False Then
MsgBox("You must at least select a PSU.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Alert")
Return
End If
End Sub
For example, if both radI3 and radI5 is not checked, i want the program to stop. Using "close()" and "stop" will close the program and i dont want that. Because after this segment, there are calculations and outputs. So i dont want the calculation to proceed and display an output unless the user checked one of the radio button.
Update: After reading the comment, someone suggested to use Return like above. But it still execute the calculation(method price, tax, total). Then i moved all the if statement for validation inside the main event and it worked. It looked like this.
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim name As String = ""
Dim phoneNum As String = ""
Dim dblCpu As Double
Dim dblRam As Double
Dim dblMotherboard As Double
Dim dblStorage As Double
Dim dblGpu As Double
Dim dblPcCase As Double
Dim dblPsu As Double
Dim price As Double
Dim tax As Double
Dim total As Double
Const service As Double = 150
If (radI3.Checked = True Or radI5.Checked = True Or radI7.Checked = True) And (radAmdAsrock.Checked = True Or radAmdGigabyte.Checked = True) Then
MessageBox.Show("You must select a motherboard that is compatible with the CPU.")
Return
End If
If (radRyzen3.Checked = True Or radRyzen5.Checked = True Or radRyzen7.Checked = True) And (radIntelAsus.Checked = True Or radIntelMsi.Checked = True) Then
MessageBox.Show("You must select a motherboard that is compatible with the CPU.")
Return
End If
If radI3.Checked = False And radI5.Checked = False And radI7.Checked = False And radRyzen3.Checked = False And radRyzen5.Checked = False And radRyzen7.Checked = False Then
MsgBox("You must at least select a CPU.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Alert")
Return
End If
If radIntelAsus.Checked = False And radIntelMsi.Checked = False And radAmdAsrock.Checked = False And radAmdGigabyte.Checked = False Then
MsgBox("You must at least select a motherboard.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Alert")
Return
End If
If radRam8gb.Checked = False And radRam16gb.Checked = False And radRam32gb.Checked = False Then
MsgBox("You must at least select a RAM.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Alert")
Return
End If
If chk120ssd.Checked = False And chk240ssd.Checked = False And chk480ssd.Checked = False And chk1tbssd.Checked = False And chk1tbhdd.Checked = False And chk2tbhdd.Checked = False Then
MsgBox("You must at least select a storage.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Alert")
Return
End If
If radGpu650.Checked = False And radGpu1050ti.Checked = False And radGpu1660ti.Checked = False Then
MsgBox("You must at least select a GPU.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Alert")
Return
End If
If radCaseTecware.Checked = False And radCaseSegotep.Checked = False And radCaseGamdias.Checked = False And radCaseLianLi.Checked = False And radCaseNzxt.Checked = False Then
MsgBox("You must at least select a case.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Alert")
Return
End If
If radpsu450.Checked = False And radpsu550.Checked = False And radpsu650.Checked = False Then
MsgBox("You must at least select a PSU.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Alert")
Return
End If
input(name, phoneNum, dblCpu, dblRam, dblMotherboard, dblStorage, dblGpu, dblPcCase, dblPsu)
price = calculatePrice(dblCpu, dblRam, dblMotherboard, dblStorage, dblGpu, dblPcCase, dblPsu)
tax = calculateTax(price)
total = calculateTotal(price, tax, service)
output(price, service, tax, total)
End Sub

OleDbAdapter errors, Hides variable in an enclosing block error

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:

>= Message Box sequence not working properly

I'm trying to make a messagebox pop up when "Trade-in Value" >= "Price." If I enter Trade-in Value:2000 and Price:12,000. The messagebox comes up, when clearly that should not be happening. After testing a bunch of numbers, it seems like the form doesn't like the number "2" in either text box. The second block is where I have my code that does not work.
I am fairly new to coding and this is my first post, taker easy boy/girls.
Entered numbers/Form
Message Box error
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GBTradeIn.Enabled = False
TxtTradeIn.Enabled = False
RBStandard.Checked = True
RBExcellent.Checked = True
End Sub
Private Sub CBTradeIn_CheckedChanged(sender As Object, e As EventArgs) Handles CBTradeIn.CheckedChanged
GBTradeIn.Enabled = True
TxtTradeIn.Enabled = True
If CBTradeIn.Checked = (False) Then
GBTradeIn.Enabled = False
TxtTradeIn.Enabled = False
RBExcellent.Checked = True
TxtTradeIn.Text = ""
End If
End Sub
Private Sub BtnCalculate_Click(sender As Object, e As EventArgs) Handles BtnCalculate.Click
Try
If CBTradeIn.Checked = (False) Then
TxtTradeIn.Text = 0
End If
If RBExcellent.Checked Then
TxtTradeInAllowance.Text = FormatCurrency(TxtTradeIn.Text * 1)
ElseIf RBGood.Checked Then
TxtTradeInAllowance.Text = FormatCurrency(TxtTradeIn.Text * 0.9)
ElseIf RBFair.Checked Then
TxtTradeInAllowance.Text = FormatCurrency(TxtTradeIn.Text * 0.8)
ElseIf RBPoor.Checked Then
TxtTradeInAllowance.Text = FormatCurrency(TxtTradeIn.Text * 0.7)
End If
Catch
MessageBox.Show("Enter valid Trade-In value")
End Try
Dim Exterior As Decimal
Dim Accessories As Decimal
If CBPremiumStereo.Checked And CBLeatherInterior.Checked And CBGPS.Checked Then
Accessories = 3154.4
ElseIf CBPremiumStereo.Checked And CBLeatherInterior.Checked Then
Accessories = 1413.17
ElseIf CBPremiumStereo.Checked And CBGPS.Checked Then
Accessories = 2166.99
ElseIf CBGPS.Checked And CBLeatherInterior.Checked Then
Accessories = 2728.64
ElseIf CBPremiumStereo.Checked Then
Accessories = 425.76
ElseIf CBLeatherInterior.Checked Then
Accessories = 987.41
ElseIf CBGPS.Checked Then
Accessories = 1741.23
End If
If RBStandard.Checked = True Then
Exterior = 0
ElseIf RBPearlized.Checked = True Then
Exterior = 345.72
ElseIf RBCustom.Checked = True Then
Exterior = 599.99
End If
TxtAccessoriesAndFinish.Text = FormatCurrency(Accessories + Exterior)
Try
Dim total As Decimal
Dim TradeIn As Decimal
Dim AccessoriesandExterior As Decimal
Dim Subtotal As Decimal
total = TxtPrice.Text
TradeIn = TxtTradeInAllowance.Text
AccessoriesandExterior = TxtAccessoriesAndFinish.Text
TxtSubtotal.Text = FormatCurrency(total + AccessoriesandExterior - TradeIn)
Subtotal = TxtSubtotal.Text
TxtSalesTax.Text = FormatCurrency((Subtotal + TradeIn) * 0.08)
TxtAmountDue.Text = FormatCurrency(Subtotal + TxtSalesTax.Text)
Catch
TxtAccessoriesAndFinish.Text = ""
TxtAmountDue.Text = ""
TxtTradeIn.Text = ""
TxtSubtotal.Text = ""
TxtSalesTax.Text = ""
TxtPrice.Text = ""
TxtTradeInAllowance.Text = ""
MessageBox.Show("Enter a valid price")
End Try
>
If TxtTradeIn.Text >= TxtPrice.Text Then
TxtAccessoriesAndFinish.Text = ""
TxtAmountDue.Text = ""
TxtTradeIn.Text = ""
TxtSubtotal.Text = ""
TxtSalesTax.Text = ""
TxtPrice.Text = ""
TxtTradeInAllowance.Text = ""
MessageBox.Show("Trade in value can't be higher than or equal to price")
End If
If CBTradeIn.Checked = (False) Then
TxtTradeIn.Text = ""
End If
End Sub
>
Private Sub BtnClear_Click(sender As Object, e As EventArgs) Handles BtnClear.Click
TxtAccessoriesAndFinish.Text = ""
TxtAmountDue.Text = ""
TxtTradeIn.Text = ""
TxtSubtotal.Text = ""
TxtSalesTax.Text = ""
TxtPrice.Text = ""
RBStandard.Checked = True
RBExcellent.Checked = True
CBPremiumStereo.Checked = False
CBLeatherInterior.Checked = False
CBGPS.Checked = False
CBTradeIn.Checked = False
TxtTradeInAllowance.Text = ""
End Sub
End Class
Instead of
If TxtTradeIn.Text >= TxtPrice.Text Then
use
If CDec(TxtTradeIn.Text) >= CDec(TxtPrice.Text) Then
CDec() converts the text inside the brackets to a decimal, allowing you to do numerical comparison rather than string comparison.
However, you must be careful: CDec() will return an error if you try to convert a non decimal to a decimal, such as a string, so you will have to check that the user has entered a valid decimal in the textboxes

Variable is used before it's been assigned a value and now data doesn't filter

So I have code that filters a datatable by multiple criteria. Every other criteria works fine but those are based on textboxes. so the code is just
Dim SubjFilter As String = "Subjects = '" & TxtSubj.Text & " '"
and then is identical to the bottom of the code below. That prints the row in the listbox just fine, but when i try to do it with radio buttons it can't seem to find the criteria. In the CSV every row in the 4th column has a piece of info that is either 75+ or 85+ or something, so I know that's not the issue. No error is coming up it's just a case of it not being able to find anything in that category or maybe something wrong with how i'm printing it in the listbox. Any sort of insight would be appreciated as i'm lost right now.
Dim ATARFilter As String
If RBtn70.Checked = True Or
Rbtn75.Checked = True Or
RBtn80.Checked = True Or
Rbtn85.Checked = True Or
Rbtn90.Checked = True Or
Rbtn95.Checked = True Then 'if any of the radiobuttons are checked then the same printing process as before is done
If RBtn70.Checked = True Then
ATARFilter = "ATAR = '70+'"
ElseIf Rbtn75.Checked = True Then
ATARFilter = "ATAR = '75+'"
ElseIf RBtn80.Checked = True Then
ATARFilter = "ATAR = '80+'"
ElseIf Rbtn85.Checked = True Then
ATARFilter = "ATAR = '85+'"
ElseIf Rbtn90.Checked = True Then
ATARFilter = "ATAR = '90+'"
ElseIf Rbtn95.Checked = True Then
ATARFilter = "ATAR = '95+'" 'all of these just set the string value of the filter to be equal to whatever is on the RadioButton
Dim FilteredRowsATAR As DataRow() = TutorTable.Select(ATARFilter)
For Each row As DataRow In FilteredRowsATAR
ListBox1.Items.Add(String.Format("{0}, {1}, {2}, {3}, {4}, {5}", row("Name"), row("Age"), row("Subjects"), row("ATAR"), row("Location"), row("PhNumber")))
Next
End If
End If
This bit of code requires Imports System.Linq . Checking Is Nothing says nothing is checked
Private Sub OPCode()
Dim ATARFilter As String = ""
Dim rButton As RadioButton = GroupBox1.Controls.OfType(Of RadioButton).FirstOrDefault(Function(r) r.Checked = True)
If rButton Is Nothing Then
MessageBox.Show("Please make a selection.")
Exit Sub
Else
ATARFilter = rButton.Text 'or if the exact text cannot not appear
' in the text of the radio button then store it in the .Tag property
'at design time and change code to = CStr(rButton.Tag)
End If
Dim FilteredRowsATAR As DataRow() = TutorTable.Select(ATARFilter)
For Each row As DataRow In FilteredRowsATAR
ListBox1.Items.Add(String.Format("{0}, {1}, {2}, {3}, {4}, {5}", row("Name"), row("Age"), row("Subjects"), row("ATAR"), row("Location"), row("PhNumber")))
Next
End Sub
Only the last condition in your ElseIf contains the code for applying the filter, you need to move it outside of the block
Dim ATARFilter As String
If RBtn70.Checked = True Or
Rbtn75.Checked = True Or
RBtn80.Checked = True Or
Rbtn85.Checked = True Or
Rbtn90.Checked = True Or
Rbtn95.Checked = True Then 'if any of the radiobuttons are checked then the same printing process as before is done
If RBtn70.Checked = True Then
ATARFilter = "ATAR = '70+'"
ElseIf Rbtn75.Checked = True Then
ATARFilter = "ATAR = '75+'"
ElseIf RBtn80.Checked = True Then
ATARFilter = "ATAR = '80+'"
ElseIf Rbtn85.Checked = True Then
ATARFilter = "ATAR = '85+'"
ElseIf Rbtn90.Checked = True Then
ATARFilter = "ATAR = '90+'"
ElseIf Rbtn95.Checked = True Then
ATARFilter = "ATAR = '95+'" 'all of these just set the string value of the filter to be equal to whatever is on the RadioButton
End If
Dim FilteredRowsATAR As DataRow() = TutorTable.Select(ATARFilter)
For Each row As DataRow In FilteredRowsATAR
ListBox1.Items.Add(String.Format("{0}, {1}, {2}, {3}, {4}, {5}", row("Name"), row("Age"), row("Subjects"), row("ATAR"), row("Location"), row("PhNumber")))
Next
End If

Object reference not set to an instance of an object for DataReader

I have a excel document and i try to fill form with value from database and i ahve some DropDownList create like that
<ContentTemplate>
<asp:DropDownList ID="DDL_Transporter" runat="server" Width = "157px"
DataSourceID="SqlDataSource2" DataTextField="transporter"
DataValueField="transporter">
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="Data Source=xxx;Initial Catalog=xxx;Persist Security Info=True;User ID=xxx;Password=xxx"
SelectCommand="SELECT [transporter] FROM [Transporter] where [active]= 'active'"></asp:SqlDataSource>
</ContentTemplate>
I don't know where is a problem but when i try to fill all boxes display that error:
Server Error in '/' Application.
Object reference not set to an instance of an object.
Line 46: End Try Line 47: Line 48:
If Header_DataReader.HasRows Then Line 49: Do
While Header_DataReader.Read Line 50:
My code is here:
If Page.IsPostBack = False Then
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con = FunctionConnection()
cmd.Connection = con
cmd.CommandText = "GetFillData"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#OrderID", RowID)
Dim Header_DataReader As SqlDataReader = Nothing
Try
con.Open()
Header_DataReader = cmd.ExecuteReader
Catch ex As Exception
End Try
If Header_DataReader.HasRows Then
Do While Header_DataReader.Read
BOX_SampleOrder.Enabled = False
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("DVMOrderNumber")) = False Then
BOX_SampleOrder.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("DVMOrderNumber"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("Requester")) = False Then
BOX_Requester.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("Requester"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("ProjectNumber")) = False Then
BOX_ProjectNumber.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("ProjectNumber"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("CostResponsable")) = False Then
BOX_PersonInvoiced.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("CostResponsable"))
End If
BOX_PersonInvoiced.Text = Generals.TrimMyString(BOX_PersonInvoiced.Text)
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("SampleOrderType")) = False Then
DDL_SampleCategory.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("SampleOrderType"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("TotalSamples")) = False Then
BOX_Quantity.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("TotalSamples"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("CostCenter")) = False Then
BOX_CostCenter.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("CostCenter"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("OrderDescription")) = False Then
BOX_Description.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("OrderDescription"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("FinalCustomerAddress")) = False Then
BOX_RecipientName.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("FinalCustomerAddress"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("TargetDate")) = False Then
BOX_DesiredDeliveryDate.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("TargetDate"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("AssemblyPlannedDate")) = False Then
BOX_AssemblyPlanedDate.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("AssemblyPlannedDate"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("LogisticsResponsable")) = False Then
DDL_Coordonator.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("LogisticsResponsable"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("ShippingMode")) = False Then
DDL_ShippingMode.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("ShippingMode"))
End If
DDL_Transporter.Items.Clear()
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("ExpressShipment")) = False Then
DDL_Transporter.Items.Add(Header_DataReader.GetValue(Header_DataReader.GetOrdinal("ExpressShipment")))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("ShippingAddress")) = False Then
BOX_ShippingAddress.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("ShippingAddress"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("Urgent")) = False Then
RBL_Urgent.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("Urgent"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("HazardousMaterial")) = False Then
RBL_Hazardous.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("HazardousMaterial"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("HasBOM")) = False Then
RBL_BOM.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("HasBOM"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("HasSerialComponents")) = False Then
RBL_SerialComponents.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("HasSerialComponents"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("PrototypeComponents")) = False Then
RBL_PrototypeComponents.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("PrototypeComponents"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("ReadyForAssembly")) = False Then
RBL_ReadyAssembly.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("ReadyForAssembly"))
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("Status")) = False Then
DDL_OrderStatus.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("Status"))
Else
DDL_OrderStatus.Text = Nothing
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("OrderType")) = False Then
DDL_OrderCategory.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("OrderType"))
Else
DDL_OrderCategory.Text = Nothing
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("ExtraQty")) = False Then
BOX_ExtraQuantity.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("ExtraQty"))
Else
BOX_ExtraQuantity.Text = Nothing
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("PackagingType")) = False Then
DDL_PackagingType.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("PackagingType"))
Else
DDL_PackagingType.Text = Nothing
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("SampleLabeling")) = False Then
BOX_SampleLabeling.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("SampleLabeling"))
Else
BOX_SampleLabeling.Text = Nothing
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("AssemblySite")) = False Then
DDL_AssemblySite.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("AssemblySite"))
Else
DDL_AssemblySite.Text = Nothing
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("AssemblyDate")) = False Then
BOX_AssemblyDate.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("AssemblyDate"))
Else
BOX_AssemblyDate.Text = Nothing
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("Destination")) = False Then
BOX_Destination.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("Destination"))
Else
BOX_Destination.Text = Nothing
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("ShippmentPlannedDate")) = False Then
BOX_ShippmentPlannedDate.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("ShippmentPlannedDate"))
Else
BOX_ShippmentPlannedDate.Text = Nothing
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("ShippmentDate")) = False Then
BOX_ShippmentDate.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("ShippmentDate"))
Else
BOX_ShippmentDate.Text = Nothing
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("ShippingCost")) = False Then
BOX_ShippingCost.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("ShippingCost"))
Else
BOX_ShippingCost.Text = Nothing
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("MaterialCost")) = False Then
BOX_TestingCost.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("MaterialCost"))
Else
BOX_TestingCost.Text = Nothing
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("ExtraNotice")) = False Then
BOX_ExtraNotice.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("ExtraNotice"))
Else
BOX_ExtraNotice.Text = Nothing
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("DelayMotive")) = False Then
BOX_DelayMotive.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("DelayMotive"))
Else
BOX_DelayMotive.Text = Nothing
End If
If Header_DataReader.IsDBNull(Header_DataReader.GetOrdinal("Comments")) = False Then
BOX_Comments.Text = Header_DataReader.GetValue(Header_DataReader.GetOrdinal("Comments"))
Else
BOX_Comments.Text = Nothing
End If
Loop
End If
If con.State = ConnectionState.Open Then
con.Close()
End If
end if
Obviously there is a problem with this code:
con.Open()
Header_DataReader = cmd.ExecuteReader
That Header_DataReader still have value of Nothing
You can catch the exception to see what is wrong with execution of the command
Or you could do this:
If Header_DataReader IsNot Nothing Then
If Header_DataReader.HasRows Then
End If
End If