Visual Basic: Simple Counter with leading Zero - vb.net

I am trying to create a simple counter that increases when the button is clicked.
What I would like is when the counter is clicked it displays "01", "02" etc.
I can create it already with "1", "2", but I would like to have a leading zero.
I have searched and found I can do this by converting the label to a string, but I cant seem to get the value to count?
If I change "count.text = counter" to "count.text = cot" it will display "01", but wont count. I'm guessing this is due to the fact its only displaying what is currently in the string but not increasing the value?
If I could get any guidance that would be great!
Many thanks!
Dim counter As Integer = 1
Dim cot As String = String.Format("{0:00}", counter)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
counter = cot + 1
count.Text = counter
End Sub

PadLeft is the key.
Dim number as Integer = 12
Console.WriteLine(number.ToString().PadLeft(2, "0")). ' prints 12
number = 2
Console.WriteLine(number.ToString().PadLeft(2, "0")). ' prints 02

The problem is, that you don't update your formatted number properly. It's only initialized a single time.
To increment the counter, use counter += 1 or counter = counter + 1 first. This will add 1 to the current value of the integer variable. Then modify the text of your Label by calling that formatting code again: count.Text = String.Format("{0:00}", counter).

This should get you started...
it converts the string into an integer. increments the number, converts it back into a string and then checks for a leading 0, if not found it adds it.
I will let you convert it into your button click for practise, as it should help you have a good understanding of the conversion between types :)
Sub string_counter()
Dim string_counter As String
string_counter = "00"
For x = 0 To 10
Debug.Print string_counter
string_counter = Int(string_counter) + 1
string_counter = Str(string_counter)
If Left(Trim(string_counter), 1) <> "0" Then
string_counter = "0" + Trim(string_counter)
End If
Next x
End Sub

Related

How to subtract from a number with a variable amount of other numbers?

Sorry for the edits, im tired and im a moron, so heres my problem=
Lets say this is my code :
Dim ogquantity,subtractedquantity as double
Private Sub CalculateMe
ogquantity = numericupdown1.value
subtractedquantity = ogquantity - numericupdown2.value
subtractedquantity = ogquantity - numericupdown3.value
subtractedquantity = ogquantity - numericupdown4.value
subtractedquantity = ogquantity - numericupdown5.value
label1.text = subtractedquantity
End Sub
And i set "CalculateMe" as code for 1-5 numericupdowns_valuechanged
This wont output a changed value..
And the reason i have it set up like this is because in the actual code numericupdown might change subtractedquantity1 or subtractedquantity28, it is decided with a dropdown menu for each numericupdown.
something like this:
Dim item1stock, item1originalstock As Double
If itemselector1name.Text = itemdefiner1name.text Then
item1stock = item1originalstock - itemselector1quantity.value
itemselector1label.text = item1stock
End If
If itemselector2name.Text = itemdefiner1name.text Then
item1stock = item1originalstock - itemselector2quantity.value
itemselector2label.text = item1stock
End If
and i would repeat check for every item like this but if two different 'itemselectorquantity' is supposed to subtract from the same original stock quantity that i dont know how to set up.. Im trying my best here but im new to coding and bad at explanation. Thank you!
Your question is rather muddled but, as an example of the sort of thing you might do if you want to use zero, one or more of a set of controls based on another set of controls, consider this example that uses CheckBoxes to specify which NumericUpDowns to subtract from an initial quantity:
Private Function SubtractCheckedValues(value As Decimal) As Decimal
Dim checkBoxes = {CheckBox1, CheckBox2, CheckBox3, CheckBox4}
Dim numericUpDowns = {NumericUpDown1, NumericUpDown2, NumericUpDown3, NumericUpDown4}
For i = 0 To checkBoxes.GetUpperBound(0)
If checkBoxes(i).Checked Then
value -= numericUpDowns(i).Value
End If
Next
Return value
End Function

How to fix previous item of a variable gets sent instead of the current one

I have a vb.net program that keeps track of people that bought raffle tickets and also keeps track of their phone numbers. When I go to add a new person(via a for loop) it gets the number of tickets they bought and adds that amount of there name and number to an array. But when I click it, it adds one extra of the prevoius name and number I had put in.
I have tried moving the place where the variable assignment takes place.
I tried to null the variable and reassign it.
Button Click
Public Sub BtnAddtckt_Click(sender As Object, e As EventArgs) Handles
BtnAddtckt.Click
Reset()
Dim MNES As String = Nameinput.Text.ToString
Dim NUMES As String = Numinput.Text.ToString
Dim LenPrev = ApplicantsName.Length - 1
Dim LenNext = (LenPrev) + (NumEntries.Value - 1)
ReDim Preserve ApplicantsName(LenNext)
ReDim Preserve ApplicantsNum(LenNext)
For Subs As Integer = LenPrev To LenNext
ApplicantsNum(Subs) = NUMES
ApplicantsName(Subs) = MNES
Next
LbltotalRegistered.Text = (ApplicantsName.Length - 1).ToString
For nme As Integer = 0 To (ApplicantsName.Length - 1)
Form2.LBname.Items.Add(ApplicantsName(nme).ToString)
Next
For nem As Integer = 0 To (ApplicantsNum.Length - 1)
Form2.LBnum.Items.Add(ApplicantsNum(nem).ToString)
Next
End Sub
I expect it to not add an extra person to each aray.

Using check digit algorithm to determine whether a value inputed is valid?

I am writing code for a form that is supposed to determine whether a value inputted by the user is valid as a check digit. They input a 13 digit number and it should determine whether or not the last value is valid as a check digit. I have written in the code for the check digit algorithm but I'm having trouble with comparing the value that the algorithm found with what the user input. I have tried using the substring method to compare the 13th number given by the user with the check digit that the algorithm determined but I am having issues with the syntax of everything.
This is the code I have been working on:
Private Sub btnValidate_Click(sender As Object, e As EventArgs) Handles btnValidate.Click
Dim intDigit As Integer
Dim intTotalOdd As Integer
Dim intTotalEven As Integer
Dim intGrandTotal As Integer
Dim intRemainder As Integer
Dim intCheckDigit As Integer
If txtNumber.Text.Length = 13 Then
For intOdd As Integer = 1 To 11 Step 2
intTotalOdd += (intDigit * 3)
Next intOdd
For intEven As Integer = 0 To 10 Step 2
intTotalEven += intDigit
Next intEven
intGrandTotal = intTotalOdd + intTotalEven
intRemainder = intGrandTotal Mod 10
If intRemainder <> 0 Then
intCheckDigit = 10 - intRemainder
End If
If txtNumber.Text.Substring(12, 13) = intCheckDigit Then
lblStatus = "Valid"
Else
lblStatus = "Not Valid"
End If
End If
End Sub
I think the way I'm doing it should work but I don't have very much to reference on how I would go about making the syntax work. Will the way that I'm trying to do it work or do I need to go about it in a different way?

generate numbers between set values vb.net

I am creating a program to generate numbers between a list of values.
Problem I am having is if the first number stats with a smaller value than the second value it will create an error, such as 1000 and 32 will say it doesnt work, or 532 and 64
I do not understand why or how to fix it
Private Sub Generate_Click(sender As System.Object,
e As System.EventArgs) Handles Generate.Click
'Displays to enter correct information if lower is <=
If Upper.Text <= Lower.Text Or Lower.Text >= Upper.Text Then
List.Items.Clear()
List.Items.Add("Please enter correct info Upper # higher value than Lower #")
Else
'If Upper range is higher than lower range then display numbers until total value is displayed
List.Items.Clear()
Number.Text = ""
Dim i As Integer = Lower.Text
Do While i <= Upper.Text 'Loop generates the numbers between values specified
List.Items.Add(i)
i += 1
Loop
'Select a random value from the list generated
Dim myRandom As New Random
Dim b As Integer = List.Items.Count
Dim chosenItem As System.Object = List.Items.Item(myRandom.Next(b))
Number.Text = chosenItem.ToString
End If
End Sub
Basically you have to compare numeric value you are comparing string so it is happening.
And 'or' condition is not required in if statement so omit it.
please replace you code as follows.
if System.Convert.ToInt32(Upper.Text) <= System.Convert.ToInt32(Lower.Text) Then
List.Items.Clear()
List.Items.Add("Please enter correct info Upper # higher value than Lower #")
Else
List.Items.Clear()
Number.Text = ""
Dim i As Integer = Lower.Text
Do While i <= System.Convert.ToInt32(Upper.Text) 'Loop generates the numbers between values specified
List.Items.Add(i)
i += 1
Loop
'Select a random value from the list generated
Dim myRandom As New Random
Dim b As Integer = List.Items.Count
Dim chosenItem As System.Object = List.Items.Item(myRandom.Next(b))
Number.Text = chosenItem.ToString
End If
With the If clause, you are doing a string comparison on numerical values. You need to cast them to integer values. And you are doing the same comparison twice which is unnecessary. Also there is a simpler way of generating random numbers between two integers.
I would encourage you to code with the "Option Strict On" declaration at the top of the page. The compiler will alert you when you attempt to make implicit conversions of which there are several in your code.
Dim iMinimum As Integer = Integer.Parse(Lower.Text)
Dim iMaximum As Integer = Integer.Parse(Upper.Text)
If iMaximum <= iMinimum Then
Number.Text = "Please enter correct info Upper # higher value than Lower #"
Else
Dim randomObject As Random = New Random
Number.Text = randomObject.Next(iMinimum, iMaximum).ToString
End If

integer to string problems

I'm trying to make a slot machine program. This procedure that I'm trying to do will assign a name to 3 randomly generated numbers. For some reason I'm getting a conversion error saying that it cant convert the integer to a string. I tried cstr() as well but the problem persisted
Sub GenerateNumbers()
Dim numbers(2) As Integer
Dim names(5) As String
Dim x As Integer
names(0) = "Cherries"
names(1) = "Oranges"
names(2) = "Plums"
names(3) = "Bells"
names(4) = "Melons"
names(5) = "Bar"
For x = 0 To 2
numbers(x) = names(CInt(Int((6 * Rnd()) + 1)))
Next x
End Sub
gives me error: conversion from string "Oranges" to type 'Integer' is not valid
The problem is that you are getting a random string from the names array and trying to assign it to numbers, which is declared as an array of integers. Of course this is not gonna work.
Apart from that, there is also the issue with out of bounds index as Eric pointed out.
Edit in response to comments:
To get the text values of those randomly generated slot machine results you just need to declare the array to store results as strings, same way as names is declared.
To be able to get the results from a separate procedure, you need to change it from Sub to Function, which is a procedure that can return a value, an array of strings in this case. Then you can call this function from your Main or any other procedure and store the returned value in a variable.
I also corrected the part with random result generation.
Module SlotMachine
Sub Main()
Dim slotResults As String()
'Get the results
slotResults = GenerateResults()
'Some further processing of results here, e.g. print results to console
For Each item In slotResults
Console.WriteLine(item)
Next
'Wait for keypress before closing the console window
Console.ReadLine()
End Sub
'Generates random results
Function GenerateResults() As String()
Dim results(2) As String
Dim names(5) As String
Dim x As Integer
names(0) = "Cherries"
names(1) = "Oranges"
names(2) = "Plums"
names(3) = "Bells"
names(4) = "Melons"
names(5) = "Bar"
Randomize()
For x = 0 To 2
results(x) = names(Int(6 * Rnd()))
Next x
Return results
End Function
End Module
Int(6 * Rnd()) will get you 0-5, if you +1, then overflow