How to make Visual Basic .NET recognize two or more digits instead of one?
When I execute it, it only validates correctly in case both numbers are one digit.
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim menorOigual As Boolean
menorOigual = numero1.Text <= numero2.Text
MsgBox(menorOigual)
End Sub
By comparing the value of the Text properties, you're comparing strings, which is why it only works with single digits (because as a string "10" comes before "3", because each character is compared in turn). You need to convert the strings to a numeric type like integer, e.g.
Convert.ToInt32(numero1.Text)
For production code, you'll probably also need to validate the conversion, so see also:
Integer.TryParse
Related
I'm trying to format two specific text boxes to show up as Sq. ft. (txt.Squareft.Text) and US currency (txtTotalprice.Text) after a calculation has been made in Visual Studio 2019 as a Windows Form Application and using visual basic code. I am using .NET framework v4.7.2 and utilizing Windows 10. The way it runs now, the numbers that show up in the textboxes are just numbers without the added Sq. ft. at the end and no currency formatting. I will also add that I am very new to VB and programming in general. Any help or suggestions?
Option Explicit On
Option Infer Off
Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
'Variables
Dim decTotalprice As Decimal
Dim decLength As Decimal
Dim decWidth As Decimal
Dim decPrice As Decimal
Dim decSquareft As Decimal
Decimal.TryParse(txtLength.Text, decLength)
Decimal.TryParse(txtWidth.Text, decWidth)
Decimal.TryParse(txtPrice.Text, decPrice)
Decimal.TryParse(txtSquareft.Text, decSquareft)
txtTotalprice.Text = decTotalprice.ToString("C2")
txtSquareft.Text = decSquareft.ToString("N2") & " Sq. ft."
' Calculate the square feet and total price
txtSquareft.Text = txtLength.Text * txtWidth.Text
txtTotalprice.Text = txtPrice.Text * txtSquareft.Text
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
' Clears all the text fields with button click
txtLength.Clear()
txtWidth.Clear()
txtPrice.Clear()
txtSquareft.Clear()
txtTotalprice.Clear()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
' Exits the form
Me.Close()
End Sub
End Class
There are two primary issues here and I feel like I bring them up at least ten times a day. Firstly, you are trying to write code without knowing what that code has to do. You've considered the end result but not the steps to get there. If you had done that then it would be obvious that your code doesn't what it's supposed to. Secondly, you clearly haven't debugged your code, which is the first thing anyone should do when they don't get the expected result. That would also let you see that your code doesn't make sense IF you considered what each line is supposed to be doing as it does it.
If this was a manual task, you would get the input from the user, perform the calculation, then display the result. Is that what you're doing here? No, it is not. First you get the user input. That's a start, but you're doing it wrong. As it stands, you would end with zero for any invalid input but you're just ignoring that. The next thing you do is display the formatted output that you haven't even calculated yet. If you had debugged, you'd have seen that both decTotalprice and decSquareft are zero at that point. You finally do the calculations, but with the raw text input instead of the numbers you already parsed, and then you display the results unformatted. You've even got a comment in your code that says that you're doing the calculation AFTER you've displayed the formatted output.
Stop writing code and think about what the required steps are to get to your desired result. Parse the user input, perform the calculations with the numeric data and not the unparsed text, then display those results with formatting. Once you have a clear idea of what you have to do AND tested that manually, then you can write code to implement that algorithm, rather than some vague idea in your head that involves a final result and little else.
You're certainly not the only person who makes these mistakes but they are elementary mistakes. They happen partly because of bad teaching in some cases, but they also happen because everyone wants to jump into the part that is sexy and fun, i.e. writing the code, but they don't want to do the harder but just as important part of considering what the code actually has to do. When they don't get the expected result, they throw their hands up without ever really having tried to fix it. If you haven't tried to understand what the code has to do, you can't have tried to make it do that.
I used this code to make month in uppercase form, the problem is that the month of May turns into 5AY
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = Strings.UCase(Format(DateTimePicker1.Value, "ddMMMyyyy"))
After realising that you were trying to actually use the month name as literal characters in your format specifier, I knew that you just had to escape those special characters. Normally, date format specifiers use the "\" character to escape but the DateTimePicker.CustomFormat property specifically requires you to wrap escaped characters in single quotes. I just tested this and it worked as expected:
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
DateTimePicker1.CustomFormat = $"dd'{DateTimePicker1.Value.ToString("MMM").ToUpper()}'yyyy"
End Sub
If you're using an older version of VB that doesn't support string interpolation, this will do the same thing:
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
DateTimePicker1.CustomFormat = String.Format("dd'{0}'yyyy", DateTimePicker1.Value.ToString("MMM").ToUpper())
End Sub
There's no need to set the Format property in code as it won't change. Just set it once in the designer. You'll probably want to execute that same code on Load because there's no ValueChanged event when the DateTimePicker takes on the current date/time by default.
I took an entry level computer programming class this past term and I'm having problems with my final project. I have to design a program in visual basic GUI that asks the player to accurately guess a number between 1-100 within a limited number of guesses.
My first form asks the user to set the number of guesses allowed. It has one textbox and an "enter" button, among other buttons that I've gotten to work.
I'm trying to get code to work that will validate the input on the guesses allowed. Specifically, I want a message box to pop up if the player enters letters or special characters instead of numbers, or enters a number less than zero, or greater than twenty. Here's what I have:
Public Class Noofguesses
Shared maxguesscnt As Integer
Private Sub Numberofguesses_TextChanged(sender As Object, e As EventArgs) Handles Numberofguesses.TextChanged
End Sub
Private Sub Quit_Click(sender As Object, e As EventArgs) Handles Quit.Click
End
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Form3.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Val(Numberofguesses) > 20 Then MsgBox("Number of Guesses Cannot Exceed 20")
If Val(Numberofguesses) < 0 Then MsgBox("Number of Guesses Must Be Greater Than 0")
If Not IsNumeric(Numberofguesses) Then MsgBox("Entry Cannot be Letters or Characters")
Me.Close()
Form2.Show()
End Sub
End Class
What am I doing wrong? Please let me know.
Thanks
I would generally suggest using a NumericUpDown rather than a TextBox, in which case no validation is required. As this is an assignment though, I'm guessing that validating a TextBox is a requirement. In that case, you should use Integer.TryParse to validate a String, i.e. the Text of the TextBox and convert it if it is valid. You can then test the converted value to make sure that it isn't less than zero, etc. I'm not going to write the code for you, given that this is homework, but that should be enough for you to do it yourself or, if you feel you must, find examples online.
I am using the Graph Control made by a user named "Aeonhack" in my .NET application. When adding, let's say, a point with the size 9, it has to be a Single like 9.0F.
So I want a function that converts an Integer like 9 into a single like 9.0F.
The normal CType won't work, and I also tried:
Private Function IntToSingle(ByVal Number As Integer) As Single
Return CType(Number & ".0F", Single)
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
GraphConnections.AddValue(IntToSingle(7))
End Sub
This gives me this error:
Conversion from string "7.0F" to type 'Single' is not valid.
How can I fix this?
Use Convert.ToSingle:
Convert.ToSingle(Number)
Or just CType, without weird string concatenation:
CType(Number, Single)
I think the confusion is with 7.0F. That is not the same thing as the string "7.0F".
Per Microsoft
Appending the literal type character F to a literal forces it to the
single data type.
You could simply use the F to force a double literal to be a single data type.
GraphConnections.AddValue(7.0F)
If, however, you receive an integer variable, then you would need to convert or cast it to a single as suggested by #MarcinJuraszek.
dim point As Integer = 7
GraphConnections.AddValue(Convert.ToSingle(point))
You can use this to convert to a single: CSng(9), though I think this only works in VB.NET.
I asked a question earlier about comparing numbers using the "And" comparison operator in If Statements and now I have been toying around with getting my head wrapped around bitwise operators. So I have written a very basic code that will allow me to see the conversion of any decimal number in binary format.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MsgBox(ConvertToBinary(-1))
End Sub
Public Function ConvertToBinary(ByVal someInteger As SByte) As String
Dim converted As String = Convert.ToString(someInteger, 2) '.PadLeft(8, "a"c)
Return converted
End Function
Notice here that I am using SByte as the paramerter - which should only contain 8 bits right? However, the message box that appears has 16 bits assigned to negative numbers. Positive numbers have the correct 8.
There is no Convert.ToString overload that takes an SByte, so the SByte is being implicitly converted to a Short.