How to display decimals from vs code to ms access - vb.net

Ok So,
im making a grading system for students as my first project with databases in vb.net
now when i get the average in decimal value and i save it to show in ms access it says it saved but when i check ms access it never saves it unless i enter values that make the average a whole number
now i went in ms access to change property of the average textbox to allow decimal places but the problem is in vs code and all my dims are already in Double
i.e
Dim average As Double
now i dont think i need to show code but i still will
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Me.Student_GradesBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(StudentGradesDataSet)
MsgBox("Success")
Catch ex As Exception
MsgBox("Please try again")
End Try
End Sub
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Try
Dim geo As Double
Dim comp As Double
Dim maths As Double
Dim sci As Double
Dim grade As String
Dim avg As Double
geo = GeographyTextBox.Text
sci = ScienceTextBox.Text
maths = MathematicsTextBox.Text
comp = ComputerTextBox.Text
If ((geo > 100) Or (sci > 100) Or (comp > 100) Or (maths > 100)) Then
MsgBox("Marks cannot be more than 100")
End
End If
avg = (geo + sci + comp + maths) / 4
If avg < 60 Then
grade = "Failed"
Else
grade = "Passed"
End If
AverageTextBox.Text = avg
GradeTextBox.Text = grade
Catch ex As Exception
MsgBox("try")
End Try
End Sub

Related

I can't find the reason for InvalidCastException

I am trying to make an app like an online shop for my project. The code is fine at first(at least for me since there's no errors indications)
But when I run it and press the "Add to Cart" button, it says InvalidCastException and says that I'm trying to convert a string to double even though I am not converting anything
This is what I have so far
Public Class Form1
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim prditem As ListViewItem
Dim price, cartprice As Integer
Dim product As String
If clbParts.SelectedItem = 0 Then
product = "Power Supply"
price = 1
End If
If clbParts.SelectedItem = 1 Then
product = "CPU"
price = 2
End If
....
If rdo512gb.Checked = True Then
product = "Hard Drive (512GB)"
price = 11
End If
If rdo1tb.Checked = True Then
product = "Hard Drice (1TB)"
price = 12
End If
cartprice = Price * numQuantity.Text
prditem = lvCart.Items.Add(product)
With prditem
.SubItems.Add(numQuantity.Text)
.SubItems.Add(cartprice)
End With
If numQuantity.Text = "0" Then
MessageBox.Show("Please put the number of items you want to add", "Cart Error")
End If
MessageBox.Show("Item/s is/are added to your cart", "Cart")
numQuantity.Text = "0"
End Sub
Private Sub btnTotal_Click(sender As Object, e As EventArgs) Handles btnTotal.Click
Dim total As Integer = 0
For i As Integer = 0 To lvCart.Items.Count - 1
Dim quantity = CInt(lvCart.Items(i).SubItems(1).Text)
Dim price = CInt(lvCart.Items(i).SubItems(2).Text)
total += quantity + price
Next
txtTotal.Text = total.ToString("N2")
End Sub
Private Sub cboPayment_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboPayment.SelectedIndexChanged
If cboPayment.SelectedItem = 0 Then
Label10.Enabled = True
cboOnline.Enabled = True
Else
Label10.Enabled = False
cboOnline.Enabled = False
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MessageBox.Show("Your items are being delivered in " + txtHomeAddress.Text + ", " + txtAddress.Text + "\n Please wait for the text confirmation", "Cart Error")
End Sub
End Class
Do yourself a favor and watch a YouTube video on how to debug in Visual Studio!
What you need to do is put a Breakpoint on this line:
cartprice = Price * numQuantity.Text
convert a string to double
You're multplying a number by a String! You want to do something like this:
cartprice = Price * Convert.ToDouble(numQuantity.Text)
I'd personally do a double.TryParse to see if its valid and use the output value when performing the operation.
PS: As a challenge to yourself, try and move all the code logic to a Business Logic class, then use Bingings/BindingControls so the Presentation layer is separated from the logic. That way you can Unit Test the business logic layer!

VB.Net guess user's number from 1 to 1000

I am trying to create a guessing game that guesses the user's number from 1 to 1000. The user inputs if the number is higher or lower than the computer's guess. Based on the user's input, the computer each time halves the amount of the guess (e.g. first guess is 500, second is 250, third 125, etc, etc)
However I have encountered a problem when I am running this program. After pressing 'higher' or 'lower' for a few times, I am unable to change the output any further. I suppose this is to do with amount = amount / 2 reaching a limit where it can barely be added or subtracted into intGuess. I have tried doing amount = (amount / 2) + 1, but that sometimes doesn't allow me to get to a number.
How would I counteract this problem?
Here is my code:
Dim intGuess As Integer = 500
Dim amount As Integer = 500
Dim count As Integer = 0
Private Sub btnLower_Click(sender As Object, e As EventArgs) Handles btnLower.Click
amount = amount / 2
intGuess = intGuess - amount
lblGuess.Text = $"Is your number {intGuess} ?"
count = count + 1
End Sub
Private Sub btnHigher_Click(sender As Object, e As EventArgs) Handles btnHigher.Click
amount = amount / 2
intGuess = intGuess + amount
lblGuess.Text = $"Is your number {intGuess} ?"
count = count + 1
End Sub
Just thought I should add this, but the first guess is 500.
I play this game verbally with my young son. I tell him to guess a number from 1 to 1000 and guarantee I can guess it in 10 or fewer guesses. It is a simple binary search. You can research binary search to come up with an algorithm. It's pretty simple and I've split it up into buttons like you have. Here is my form
The code to make it work is
Private guess As Integer
Private max As Integer
Private min As Integer
Private Sub StartButton_Click(sender As Object, e As EventArgs) Handles StartButton.Click
If Integer.TryParse(MaxTextBox.Text, max) AndAlso
Integer.TryParse(MinTextBox.Text, min) AndAlso
max > min Then
makeGuess()
Else
MessageBox.Show("Error in max or min, cannot continue! Fix max and min and try again.")
End If
End Sub
Private Sub HigherButton_Click(sender As Object, e As EventArgs) Handles HigherButton.Click
min = guess
makeGuess()
End Sub
Private Sub LowerButton_Click(sender As Object, e As EventArgs) Handles LowerButton.Click
max = guess
makeGuess()
End Sub
Private Sub JustRightButton_Click(sender As Object, e As EventArgs) Handles JustRightButton.Click
MessageBox.Show($"That's right, I found your number, it is {guess}!")
End Sub
Private Sub makeGuess()
guess = CInt((max - min) / 2 + min)
GuessLabel.Text = guess.ToString()
End Sub

VB.NET - Getting a NaN result, can't figure out why

I'm trying to write a simple GPA calculator where the user enters a grade from an item on a combobox (A,B,C,D,F) and the credit hours of the course, and the calculation will output into a textbox. However, I keep getting a NaN result within the textbox and I can't for the life of me understand why. I've only got a bit of programming experience, so I'd appreciate any help!
Public Class Form1
Public points As Double, hours As Integer
Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click
Dim gpaPoints As Double
Dim creditHours As Integer
Dim grade As String
If cmbGrades.SelectedIndex < 0 Then
MsgBox("Please select a grade.")
Exit Sub
ElseIf txtHours.Text = "" Then
MsgBox("Please enter credit hours.")
Else
grade = cmbGrades.SelectedItem
creditHours = CInt(txtHours.Text)
gpaPoints = CalcGPA(grade, creditHours)
points += gpaPoints
hours += creditHours
ClearList()
End If
End Sub
Public Sub ClearList()
cmbGrades.SelectedIndex = -1
cmbGrades.Text = "Select a grade"
txtHours.Text = ""
End Sub
Public Function CalcGPA(grade As String, creditHours As Integer)
Dim gpaPoints As Double
Select Case (grade)
Case "A"
gpaPoints = 4
Case "B"
gpaPoints = 3
Case "C"
gpaPoints = 2
Case "D"
gpaPoints = 1
Case Else
gpaPoints = 0
End Select
Return gpaPoints
End Function
Private Sub btnGpa_Click(sender As Object, e As EventArgs) Handles btnGpa.Click
Dim calcGpa As Double = points / hours
txtGpa.Text = FormatNumber(calcGpa, 2)
End Sub
End Class
I basically have the record button which works fine clearing the list and allows someone to enter a second grade, but the calculate button is not working and I can't figure this out. I sincerely appreciate any help.
As a general rule of thumb, if you are getting 'NaN's you can check for the following :
A calculation with any NaN somewhere will give out a NaN
The 0 / 0 division will give a NaN if it's with floating points number. You have a floating point division, so you can check here if your values are not zero when you do your calculation.
Private Sub btnGpa_Click(sender As Object, e As EventArgs) Handles btnGpa.Click
'Dim calcGpa As Double = points / hours '(**did you assign values here?** if not remove this)
dim answer as double = 0
CalcGPA(cmbGrades.SelectedValue, txtHours.Text )
txtGpa.Text = FormatNumber(answer, 2)
End Sub

multiple inputs in text box not totaling

I got another super basic question, im trying to total the subtotals of every entry in the txtPrice.Text the user enters, and then refresh the other lables with the updated tax, shipping, and grand total. Its not totaling the subTotal, everything else works fine. Whats up with that?
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Dim sglSub As Single
Dim sglTotal As Single
Dim sglSalesTax As Single
Const TAX_RATE As Single = 0.02
Dim bytShippingCharge As SByte = 10
Dim sglCompTotal As Single
Single.TryParse(txtPrice.Text, sglSub)
sglTotal += sglSub
lblSubTotal.Text = sglTotal.ToString("C2")
sglSalesTax = (sglTotal * TAX_RATE)
lblTax.Text = sglSalesTax.ToString("C2")
If sglTotal >= 100 Then
bytShippingCharge = 0
End If
lblShipping.Text = bytShippingCharge.ToString("C2")
sglCompTotal = (sglTotal + sglSalesTax + bytShippingCharge)
lblTotal.Text = sglCompTotal.ToString("C2")
End Sub
Tips
In this line:
sglTotal += sglSub
-Every time you work with a total initialize it to zero before adding a value to it. If not it can leads to undesired result.
-When working with currency is better to use a decimal type instead.
If you want a variable keeps its value declare it shared.
This a little example of how you can use a shared field
Public Class Form1
Shared total As Decimal = 0D
Shared Sub calc()
total += 2
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
calc()
Label1.Text = total.ToString
End Sub
End Class

Array as structure members Assignment Student Test Scores

ASSIGNMENT
A teacher has six students and wants you to create an application that stores their grade data in a file and prints a grade report. The application should have a structure that stores the following student data: Name (a string), Test Scores (an array of five Doubles), and Average (a Double). Because the teacher has six students, the application should use an array of six structure variables.
The application should allow the user to enter data for each student, and calculate the average test score.
The user should be abled to save the data to a file, read the data from the file, and print a report showing each student's test scores and average score. The form shows a meny system. You may you buttons instead if you prefer.
Input validation: Do not accept test scores less that zero or greater than 100.
]
my understanding of how it should be structured
For the Moment I don't understand that in the FOR EACH loop I can not accumulate total it saying that I am not allowed to use + . I am trying to get scores from txtScore1Std1 (For example) assign it to dblTestScoreArray and using for each loop to find sum of those 5 score and when find average and output it to lbl average for student number 1.
Code Module:
Module StudentTestScoresModule
Const intMAX_SUBSCRIPT_STUDENT As Integer = 6
Const intMAX_SUBSCRIPT_STUDENT_SCORES As Integer = 5
'create structure
Public Structure StudentData
Dim strName As String
Dim dblTestScoresArray() As Double
Dim dblAverage As Double
End Structure
Dim dblTotalStd1 As Double
Dim dblScore As Double
Dim StudentsArray(intMAX_SUBSCRIPT_STUDENT) As StudentData
Sub StudentNameDataInput()
StudentsArray(0).strName = MainForm.txtStdName1.Text
StudentsArray(1).strName = MainForm.txtStdName2.Text
StudentsArray(2).strName = MainForm.txtStdName3.Text
StudentsArray(3).strName = MainForm.txtStdName4.Text
StudentsArray(4).strName = MainForm.txtStdName5.Text
StudentsArray(5).strName = MainForm.txtStdName6.Text
End Sub
Sub StudentScoreDataInput()
For intIndex = 0 To intMAX_SUBSCRIPT_STUDENT
ReDim StudentsArray(intIndex).dblTestScoresArray(4)
Next
'test scores for first student
StudentsArray(0).dblTestScoresArray(0) = CDbl(MainForm.txtScore1Std1.Text)
StudentsArray(1).dblTestScoresArray(1) = CDbl(MainForm.txtScore2Std1.Text)
StudentsArray(2).dblTestScoresArray(2) = CDbl(MainForm.txtScore3Std1.Text)
StudentsArray(3).dblTestScoresArray(3) = CDbl(MainForm.txtScore4Std1.Text)
StudentsArray(4).dblTestScoresArray(4) = CDbl(MainForm.txtScore5Std1.Text)
For Each i As StudentData In StudentsArray
dblTotalStd1 += i
Next
dblAverage = dblTotalStd1 / intMAX_SUBSCRIPT_STUDENT_SCORES
MainForm.lblAvgStd1.Text = (dblAverage.ToString)
End Sub
Sub CalculateAverage()
End Sub
End Module
Code Main Form:
Public Class MainForm
Private Sub mnuHelpAbout_Click(sender As Object, e As EventArgs) Handles mnuHelpAbout.Click
'about program
MessageBox.Show("Student test score calculator version 0.1")
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
' Close(program)
Me.Close()
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
StudentScoreDataInput()
End Sub
End Class
just by looking, without testing, what you need to do is;
'untested code
For Each i As StudentData In StudentsArray
For Each S as Double in i.dblTestScoresArray
dblTotalStd1 += s
Next
Next
you cannot do += on a structure, you need to do it on the member and since its an array, you need to loop through it