System.ArgumentException: 'Argument 'NPer' is not a valid value.' - vb.net

I was able to debug my coding then, when I click my "Calculate" button, the error message
System.ArgumentException: 'Argument 'NPer' is not a valid value.'
pops up (first pic). The second pic is my app. The reset button and the exit button work, but when I click the "Calculate" button it doesn't work.
Public Class Form1
Const dblMonths_Year As Double = 12
Const dblNew_Rate As Double = 0.05
Const dblUsed_Rate As Double = 0.08
Dim dblAnnualRate As Double = dblNew_Rate
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim dblVehicleCost As Double
Dim dblDownPayment As Double
Dim dblMonths As Double
Dim dblLoan As Double
Dim dblMonthlyPayment As Double
Dim dblInterest As Double
Dim dblPrincipal As Double
Dim intCount As Integer
Dim strOut As String
Dim blnInputOK As Boolean = True
If blnInputOK = True Then
dblLoan = dblVehicleCost - dblDownPayment
dblMonthlyPayment = Pmt(dblAnnualRate / dblMonths_Year, dblMonths, -dblLoan)
lstOutput.Items.Clear()
For intCount = 1 To dblMonths
dblInterest = IPmt(dblAnnualRate / dblMonths_Year, intCount, dblMonths, -dblLoan)
dblPrincipal = PPmt(dblAnnualRate / dblMonths_Year, intCount, dblMonths, -dblLoan)
strOut = "Month" & intCount.ToString("d2")
strOut &= ": payment =" & dblMonthlyPayment.ToString("n2")
strOut &= ", interest =" & dblInterest.ToString("n2")
strOut &= ", principal =" & dblPrincipal.ToString("n2")
lstOutput.Items.Add(strOut)
Next
End If
End Sub
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
radNew.Checked = True
dblAnnualRate = dblNew_Rate
lblAnualRate.Text = dblNew_Rate.ToString("p")
txtCost.Clear()
txtDownPayment.Clear()
txtMonths.Clear()
lstOutput.Items.Clear()
txtCost.Focus()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Close()
End Sub
Private Sub radNew_CheckedChanged(sender As Object, e As EventArgs) Handles radNew.CheckedChanged
If radNew.Checked = True Then
dblAnnualRate = dblNew_Rate
lblAnualRate.Text = dblNew_Rate.ToString("p")
lstOutput.Items.Clear()
End If
End Sub
Private Sub radUsed_CheckedChanged(sender As Object, e As EventArgs) Handles radUsed.CheckedChanged
If radUsed.Checked = True Then
dblAnnualRate = dblUsed_Rate
lblAnualRate.Text = dblUsed_Rate.ToString("p")
lstOutput.Items.Clear()
End If
End Sub
End Class

You need to set the variables from the input fields, preferably making sure that the user has input sensible values, for example:
Public Class Form1
Const MONTHS_PER_YEAR = 12
Const NEW_RATE = 0.05
Const USED_RATE = 0.08
Dim annualInterestRate As Double = NEW_RATE
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim vehicleCost = 0.0D
Dim downPayment = 0.0D
Dim monthsToPay = 0
Dim inputOk = Decimal.TryParse(tbCost.Text, vehicleCost) AndAlso
Decimal.TryParse(tbDownPayment.Text, downPayment) AndAlso
Integer.TryParse(tbMonthsToPay.Text, monthsToPay)
If inputOk Then
lstOutput.Items.Clear()
Dim loanAmount = vehicleCost - downPayment
Dim monthlyPayment = Pmt(annualInterestRate / MONTHS_PER_YEAR, monthsToPay, -loanAmount)
For monthNumber = 1 To monthsToPay
Dim interestPayment = IPmt(annualInterestRate / MONTHS_PER_YEAR, monthNumber, monthsToPay, -loanAmount)
Dim principalPayment = PPmt(annualInterestRate / MONTHS_PER_YEAR, monthNumber, monthsToPay, -loanAmount)
Dim strOut = $"Month {monthNumber:D2}"
strOut &= $": payment = {monthlyPayment:C2}"
strOut &= $", interest = {interestPayment:C2}"
strOut &= $", principal = {principalPayment:C2}"
lstOutput.Items.Add(strOut)
Next
End If
End Sub
' other code here
End Class
It is convention to use UPPER_SNAKE_CASE for constants. Variables should (usually) be declared at the point of use.
In VB.NET, set Option Strict On and Option Infer On for an easier programming experience.
The D is a forced literal type for a Decimal value. The Decimal type should be used for money, even though the Pmt, IPmt, and PPmt functions don't (I suspect the Decimal type wasn't available when those functions were written).
I used interpolated strings to show you how they could be used in your program: they can be useful for making code more readable.

Related

Simple if-statement logic returning a wrong value

I have the simplest of if statements to work out if a person has passed an exam or not when I run the code the result always comes up as fail.
Public Class Form1
Dim EnglishMark As Single
Dim ScienceMark As Single
Dim MathsMark As Single
Dim AverageMark As Single
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
EnglishMark = Val(txtEnglish.Text)
ScienceMark = Val(txtScience.Text)
MathsMark = Val(txtMaths.Text)
AverageMark = (EnglishMark + ScienceMark + MathsMark) / 3 / 100
If (AverageMark >= 50) Then
lblDisplay.Text = "You Passed Well Done" & Format(AverageMark, "Percent")
Else
lblDisplay.Text = "You Failed Try Again" & Format(AverageMark, "Percent")
End If
End Sub
End Class
Thanks

need histogram from these results VB.net

I need some help with the histogram. My program counted the words with three, four, five and six letters. Now I need to make simple histogram from the received answers. This is my code:
Public Class Form1
Dim tekst As String
Dim rijec() As String
Dim trazena As String
Dim brojac1 As Integer = 1
Dim brojac2 As Integer = 0
Dim brojac3 As Integer = 0
Private Sub btnUcitaj_Click(sender As Object, e As EventArgs) Handles btnUcitaj.Click
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
RichTextBox1.Text = My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)
End If
End Sub
Private Sub btnPrebroj1_Click(sender As Object, e As EventArgs) Handles btnPrebroj1.Click
tekst = RichTextBox1.Text
rijec = tekst.Split(CChar(" "))
Dim count = From x In rijec Where x.Length = 3
txtTri.Text = ("Number of words: " & count.Count.ToString())
End Sub
Private Sub btnPrebroj2_Click(sender As Object, e As EventArgs) Handles btnPrebroj2.Click
tekst = RichTextBox1.Text
rijec = tekst.Split(CChar(" "))
Dim count = From x In rijec Where x.Length = 4
txtCetiri.Text = ("Number of words: " & count.Count.ToString())
End Sub
Private Sub btnPrebroj3_Click(sender As Object, e As EventArgs) Handles btnPrebroj3.Click
tekst = RichTextBox1.Text
rijec = tekst.Split(CChar(" "))
Dim count = From x In rijec Where x.Length = 5
txtPet.Text = ("Number of words: " & count.Count.ToString())
End Sub
Private Sub btnPrebroj4_Click(sender As Object, e As EventArgs) Handles btnPrebroj4.Click
tekst = RichTextBox1.Text
rijec = tekst.Split(CChar(" "))
Dim count = From x In rijec Where x.Length = 6
txtSest.Text = ("Number of words: " & count.Count.ToString())
End Sub
i need histogram from these results from picture.
Visual Basic actually has a control called a chart which is nice for this kind of situation. I found a tutorial here if you would like to check it out.
I wrote up this function that should work with your code, all you need to do is add a data chart and call it Chart1 and call this function.
Private Sub ShowData()
Chart1.Series.Clear() ' Delete the default data series.
Dim tekst = RichTextBox1.Text
Dim rijec = tekst.Split(CChar(" "))
With Chart1.Series.Add("Word Lengths") ' Add a new series called Word Lengths
For wordLength As Integer = 3 To 6 ' Check every word length from 3 to 6
Dim count = From x In rijec Where x.Length = wordLength ' Count how many words there are
.Points.AddXY(wordLength, count.Count) ' Add a new data point
Next
End With
End Sub
Good luck, I hope this helped!
~Nic

Score not being calculated correctly

Hi I'm created a program for a project and I've now started running some tests and the score for the user isn't being calculated correctly and I believe that it can't compare the answer given to the correct answer. I'm very confused and need any help that can be given. My code looks like this, any confusing parts and I'll try and explain.
Imports System.IO
Public Class QuestionScreen
Dim score As Integer = 0
Dim count As Integer
Dim Difficulty_ext As String
Dim questions, answers As New List(Of String)()
Private i As Integer
Sub ReadFile()
If Main.Diff_DDown.Text = "Easy" Then
Difficulty_ext = "questions - Easy"
ElseIf Main.Diff_DDown.Text = "Medium" Then
Difficulty_ext = "questions - Medium"
Else
Difficulty_ext = "questions - Difficult"
End If
Randomize()
Dim countline = File.ReadAllLines("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt").Length
Dim numline As Integer
Dim values() As String
Using sr As New StreamReader("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt")
While Not sr.EndOfStream
values = sr.ReadLine().Split(","c)
questions.Add(values(0))
answers.Add(values(1))
End While
End Using
numline = Int(Rnd() * countline)
For i As Integer = 0 To numline
Question.Text = questions(i)
Act_ANS.Text = answers(i)
Next
End Sub
Private Sub Pass_Btn_Click(sender As Object, e As EventArgs) Handles Pass_Btn.Click
If count < 10 Then
Call ReadFile()
count = count + 1
Ans_TxtBx.Text = ""
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
End If
End Sub
Public Sub Submit_Btn_Click(sender As Object, e As EventArgs) Handles Submit_Btn.Click
If count < 10 Then
Call ReadFile()
count = count + 1
If Ans_TxtBx.Text = answers(i) Then
score = score + 1
End If
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
count = 0
End If
Ans_TxtBx.Text = ""
End Sub
Private Sub QuestionScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call ReadFile()
End Sub
End Class
OK..... Try this, I have debugged your code trying to leave it pretty much as you had it, there were a number of problems, nothing major just a few lines of code in the wrong place....
Imports System.IO
Public Class Form1
Dim score As Integer = 0
Dim count As Integer
Dim Difficulty_ext As String
Dim questions, answers As New List(Of String)()
Private i As Integer
Sub ReadFile()
If Diff_DDown.Text = "Easy" Then
Difficulty_ext = "questions - Easy"
ElseIf Diff_DDown.Text = "Medium" Then
Difficulty_ext = "questions - Medium"
Else
Difficulty_ext = "questions - Difficult"
End If
Randomize()
Try
Dim countline = File.ReadAllLines("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt").Length
Dim numline As Integer
Dim values() As String
' clear the list of questions and answers
answers.Clear()
questions.Clear()
'''''''''''''''''''''''''''''''''''''''''
Using sr As New StreamReader("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt")
While Not sr.EndOfStream
values = sr.ReadLine().Split(","c)
questions.Add(values(0))
answers.Add(values(1))
End While
End Using
numline = Int(Rnd() * countline)
For i = 0 To numline
Question.Text = questions(i)
Act_ANS.Text = answers(i)
Next
Catch ex As Exception
End Try
End Sub
Private Sub Pass_Btn_Click(sender As Object, e As EventArgs) Handles Pass_Btn.Click
If count < 10 Then
count = count + 1
Ans_TxtBx.Text = ""
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
End If
Call ReadFile() ' move this to the bottom
End Sub
Public Sub Submit_Btn_Click(sender As Object, e As EventArgs) Handles Submit_Btn.Click
If count < 10 Then
count = count + 1
If Ans_TxtBx.Text = answers(i - 1) Then ' need to subtract 1 here
score = score + 1
End If
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
count = 0
End If
Ans_TxtBx.Text = ""
Call ReadFile() ' move this to the bottom
End Sub
Private Sub QuestionScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call ReadFile()
End Sub
End Class

Save clicks to file

I got asked a couple of days ago how to save number of clicks you have done to each button in a program to a small file, to keep track of what is most used. Since it was ages ago i dabbled with visual basic i said i would raise the question here, so here goes.
There are 5 buttons labels Button1-Button5. When a button is clicked it should look for the correct value in a file.txt and add +1 to the value. The file is structured like this.
Button1 = 0
Button2 = 0
Button3 = 0
Button4 = 0
Button5 = 0
So when button1 is clicked it should open file.txt, look for the line containing Button1 and add +1 to the value and close the file.
I have tried looking for some kind of tutorial on this but have not found it so i'm asking the collective of brains here on Stackoverflow for some guidance.
Thanks in advance.
delete file first
new ver ..
Imports System.IO.File
Imports System.IO.Path
Imports System.IO
Imports System.Text
Public Class Form1
Dim line() As String
Dim strbild As StringBuilder
Dim arr() As String
Dim i As Integer
Dim pathAndFile As String
Dim addLine As System.IO.StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fileName As String = "myfile.txt"
Dim appPath As String = My.Application.Info.DirectoryPath
pathAndFile = Path.Combine(appPath, fileName)
If System.IO.File.Exists(pathAndFile) Then
'line = File.ReadAllLines(pathAndFile)
Else
Dim addLineToFile = System.IO.File.CreateText(pathAndFile) 'Create an empty txt file
Dim countButtons As Integer = 5 'add lines with your desired number of buttons
For i = 1 To countButtons
addLineToFile.Write("Button" & i & " = 0" & vbNewLine)
Next
addLineToFile.Dispose() ' and close file
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
writeToFile(1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
writeToFile(2)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
writeToFile(3)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
writeToFile(4)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
writeToFile(5)
End Sub
Public Sub writeToFile(buttonId As Integer)
Dim tmpButton As String = "Button" & buttonId
strbild = New StringBuilder
line = File.ReadAllLines(pathAndFile)
Dim f As Integer = 0
For Each lineToedit As String In line
If InStr(1, lineToedit, tmpButton) > 0 Then
Dim lineSplited = lineToedit.Split
Dim cnt As Integer = lineSplited.Count
Dim newVal = addCount(CInt(lineSplited.Last()))
lineSplited(cnt - 1) = newVal
lineToedit = String.Join(" ", lineSplited)
line(f) = lineToedit
End If
f = f + 1
Next
strbild = New StringBuilder
'putting together all the reversed word
For j = 0 To line.GetUpperBound(0)
strbild.Append(line(j))
strbild.Append(vbNewLine)
Next
' writing to original file
File.WriteAllText(pathAndFile, strbild.ToString())
Me.Refresh()
End Sub
' Reverse Function
Public Function ReverseString(ByRef strToReverse As String) As String
Dim result As String = ""
For i As Integer = 0 To strToReverse.Length - 1
result += strToReverse(strToReverse.Length - 1 - i)
Next
Return result
End Function
Public Function addCount(ByVal arr As Integer) As Integer
Return arr + 1
End Function
End Class
Output in myfile.txt
Button1 = 9
Button2 = 2
Button3 = 4
Button4 = 0
Button5 = 20
Create a vb winform Application
Drag on your form 5 buttons (Button1, Button2, ... etc)
copy that :
Imports System.IO.File
Imports System.IO.Path
Imports System.IO
Imports System.Text
Public Class Form1
Dim line() As String
Dim strbild As StringBuilder
Dim arr() As String
Dim i As Integer
Dim pathAndFile As String
Dim addLine As System.IO.StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fileName As String = "myfile.txt"
Dim appPath As String = My.Application.Info.DirectoryPath
pathAndFile = Path.Combine(appPath, fileName)
If System.IO.File.Exists(pathAndFile) Then
line = File.ReadAllLines(pathAndFile)
Else
Dim addLineToFile = System.IO.File.CreateText(pathAndFile) 'Create an empty txt file
Dim countButtons As Integer = 5 'add lines with your desired number of buttons
For i = 1 To countButtons
addLineToFile.Write("Button" & i & " = 0" & vbNewLine)
Next
addLineToFile.Dispose() ' and close file
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
writeToFile(1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
writeToFile(2)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
writeToFile(3)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
writeToFile(4)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
writeToFile(5)
End Sub
Public Sub writeToFile(buttonId As Integer)
Dim tmpButton As String = "Button" & buttonId
strbild = New StringBuilder
line = File.ReadAllLines(pathAndFile)
i = 0
For Each lineToedit As String In line
If lineToedit.Contains(tmpButton) Then
Dim lineSplited = lineToedit.Split
Dim newVal = addCount(CInt(lineSplited.Last()))
'lineToedit.Replace(lineSplited.Last, newVal)
lineToedit = lineToedit.Replace(lineToedit.Last, newVal)
line(i) = lineToedit
End If
i = i + 1
Next
strbild = New StringBuilder
'putting together all the reversed word
For j = 0 To line.GetUpperBound(0)
strbild.Append(line(j))
strbild.Append(vbNewLine)
Next
' writing to original file
File.WriteAllText(pathAndFile, strbild.ToString())
End Sub
' Reverse Function
Public Function ReverseString(ByRef strToReverse As String) As String
Dim result As String = ""
For i As Integer = 0 To strToReverse.Length - 1
result += strToReverse(strToReverse.Length - 1 - i)
Next
Return result
End Function
Public Function addCount(ByVal arr As Integer) As Integer
Return arr + 1
End Function
End Class
Have fun ! :)CristiC777
try this on vs2013
change If confition
line = File.ReadAllLines(pathAndFile)
i = 0
For Each lineToedit As String In line
If InStr(1, lineToedit, tmpButton) > 0 Then
'If lineToedit.Contains(tmpButton) = True Then
Dim lineSplited = lineToedit.Split
Dim newVal = addCount(CInt(lineSplited.Last()))
lineToedit = lineToedit.Replace(lineToedit.Last, newVal)
line(i) = lineToedit
End If
i = i + 1
Next

code modified lines added

I have data like this
date value
24sep2014 2:23:01 0.1
24sep2014 2:23:02 0.3
24sep2014 2:23:03 0.2
24sep2014 2:23:04 0.3
These are not coma seprated value. I wanted to write in CSV file. Apend the value for next row.
1)How to open file only once here. when it run next time file name has to change to other name
2) How to append the next values
Imports System
Imports System.IO.Ports
Imports System.ComponentModel
Imports System.Threading
Imports System.Drawing
Imports System.Windows.Forms.DataVisualization.Charting
Public Class Form1
Dim myPort As Array
Dim Distance As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myPort = IO.Ports.SerialPort.GetPortNames()
PortComboBox.Items.AddRange(myPort)
BaudComboBox.Items.Add(9600)
BaudComboBox.Items.Add(19200)
BaudComboBox.Items.Add(38400)
BaudComboBox.Items.Add(57600)
BaudComboBox.Items.Add(115200)
ConnectButton.Enabled = True
DisconnectButton.Enabled = False
Chart1.Series.Clear()
Chart1.Titles.Add("Demo")
'Create a new series and add data points to it.
Dim s As New Series
s.Name = "CURRENT"
s.ChartType = SeriesChartType.Line
End Sub
Private Sub ConnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectButton.Click
SerialPort1.PortName = PortComboBox.Text
SerialPort1.BaudRate = BaudComboBox.Text
SerialPort1.Open()
Timer1.Start()
Timer2.Start()
'lblMessage.Text = PortComboBox.Text & " Connected."
ConnectButton.Enabled = False
DisconnectButton.Enabled = True
End Sub
Private Sub DisconnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisconnectButton.Click
SerialPort1.Close()
DisconnectButton.Enabled = False
ConnectButton.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim counter As Integer
counter = 0
Try
SerialPort1.Write("c")
System.Threading.Thread.Sleep(250)
Dim k As Double
Dim distance As String = SerialPort1.ReadLine()
k = CDbl(distance)
ListBoxSensor.Text = k
Dim s As New Series
s.Points.AddXY(1000, k)
Chart1.Series.Add(s)
Dim headerText = ""
Dim csvFile As String = Path.Combine(My.Application.Info.DirectoryPath, "Current.csv")
If Not File.Exists(csvFile)) Then
headerText = "Date& time ,Current"
End If
Using outFile = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
If headerText.Length > 0 Then
outFile.WriteLine(headerText)
End If
Dim y As String = DateAndTime.Now
Dim x As String = y + "," + distance
outFile.WriteLine(x)
End Using
Catch ex As Exception
End Try
End Sub
Private Sub Relay_ON_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Relay_ON.Click
SerialPort1.Write("1")
End Sub
Private Sub Relay_Off_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Relay_Off.Click
SerialPort1.Write("0")
End Sub
End Class
Here i am opening file again and again. that reason i can store only one value
# steve error
The second parameter of OpenTextFileWriter allows to append instead of overwrite your file.
So it is simply a matter to check if the file exists (so you insert the header names) and then write your data
Dim headerText = ""
Dim csvFile As String = Path.Combine(My.Application.Info.DirectoryPath, "Current.csv")
If Not File.Exists(csvFile) Then
headerText = "Date& time ,Current"
End If
Using outFile = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
If headerText.Length > 0 Then
outFile.WriteLine(headerText)
End If
Dim y As String = DateAndTime.Now
Dim x As String = y + "," + distance
outFile.WriteLine(x)
End Using
Notice the Using Statement to be sure to close and dispose the file resource also in case of exceptions.
However given the simple text that need to be written you could also choose to use the method WriteAllText
Dim headerText = ""
Dim csvFile As String = Path.Combine(My.Application.Info.DirectoryPath, "Current.csv")
If Not File.Exists(csvFile) Then
headerText = "Date& time ,Current" & Environment.NewLine
End If
Dim y As String = DateAndTime.Now
Dim x As String = headerText & y & "," + distance & Environment.NewLine
My.Computer.FileSystem.WriteAllText(csvFile, x, True)