VB textbox and width prob - vb.net

hi there im trying to design a section in my program that builds layers represented by rectangles, depending on the sizes inputed will decide upon the outcome of the rectangle width. Im having a problem when entering < 0 it will revert to 1 or 0.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim rectangle As Integer
rectangle = Val(TextBox1.Text)
TextBox1.Text = Convert.ToString(rectangle)
Form2.RectangleShape1.Width = Val(TextBox1.Text)
If Val(TextBox1.Text) >= 1.0 Or Val(TextBox1.Text) <= 1.5 Then
Form2.RectangleShape1.Width = 75
End If
If Val(TextBox1.Text) >= 1.5 Then
Form2.RectangleShape1.Width = 120
End If
If Val(TextBox1.Text) <= 1.0 Then
Form2.RectangleShape1.Width = 55
End If
Form2.RectangleShape1.Show()
Me.Hide()

It's hard to say with the provided information and I don't understand exactly what you are doing but a few things seems wrong there.
The you lost me part
Let's look at this first :
Dim rectangle As Integer
rectangle = Val(TextBox1.Text)
TextBox1.Text = Convert.ToString(rectangle)
Form2.RectangleShape1.Width = Val(TextBox1.Text)
So you declare an integer
Take the text of some textbox and select only the numbers from it by taking out characters
You assign back that value in the Textbox with a ToString() on the Integer
You assign the value of the textbox once again taking out characters (you already did that)
You can resume this line with :
Form2.RectangleShape1.Width = CDbl(Val(TextBox1.Text))
I changed the conversion to doubles because I'm certain you want decimals. Integers can't have decimals. Without decimals, these two conditions would be the exact same thing :
If Val(TextBox1.Text) >= 1.0 Or Val(TextBox1.Text) <= 1.5 Then
Form2.RectangleShape1.Width = 75
End If
If Val(TextBox1.Text) >= 1.5 Then
Form2.RectangleShape1.Width = 120
End If
Since you can either have 1 or 2. (So checking if it's between 1 and 1.5 OR 1.5 and 2 is pointless).
Val
You probably know this but val will return the numbers in a string. So as I asked in the comments, why don't you prevent the user from inputting something else than numbers ?
Let's say you want to have this as result : "< 0".
If you prevent letter and symbol he will have to input only "0"
If you do it like you're doing right now he will input "< 0" the val function will only return "0" so telling me you need the "<" is against your current logic.
But I want the number and the symbol...
Don't worry. If you are make sure the user will only input what you want (by putting restriction on the possible characters to input), you can catch the whole content of the textbox.
If myTextBox.Text = "< 1.5" Then
'Do something cool
Else If myTextBox.Text = "< 0" Then
'Do something cooler
Else
'Do nothing
End If

Related

VB.NET Divisions problems

First of all, I would like you to know that I am really rookie on this platform and in vb.net language. I have a question, I wanted to ask you, since I couldn't make any progress in about 3 hours. I think it's very simple for someone who knows.
If the number entered from the textbox is odd, multiply by 3 and add 1, if it is double, this process will be divided by 2, and this process should continue until the number is "1". I try to write the code of the program that finds how many steps this process takes (number of processes), the maximum value of the number during the process and the number that the number always reaches 1 in pairs with VB.NET.
Is there anyone who can help? I want you to know that I was really struggling, trying to learn, but not enough
As I said, I scribbled something, but I am not even on the right track.
enter image description here
enter code here
Dim number1 As Double
Dim tislem As Double
Dim result As Double
Dim çislem As Double
Dim i As Double
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
number1 = TextBox1.Text
çislem = number1 / 2
tislem = number1 * 3 + 1
If number1 Mod (2) = 1 Then
result = tislem
MessageBox.Show("sayı tektir" + result.ToString())
For i = 1 To result = 0
result = number1 / 2
Next i
MessageBox.Show("sayı tektir" + result.ToString())
Else MessageBox.Show("sayı çifttir")
End If
End Sub
I'm not sure if I understood exactly what you're trying to do (neither of us have english as a first language it seems). I'm still trying, but make sure that you understand what I'm doing or I may lead you off target.
It seems to me that the worst problem here is using a For loop instead of a While loop. You could also do without some of these variables. Here's some code to give you a hand:
' I suggest that you add these two lines at the very top of your code
' It'll force you to type your variables, which is a great way to avoid all kind of mistakes
Option Explicit On
Option Strict On
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Here I'm protecting you against errors caused if the user enters a non-numeric
' Your teached probably didn't ask for this but it's good to know nonetheless
If Not String.IsNullOrWhiteSpace(TextBox1.Text) AndAlso IsNumeric(TextBox1.Text) Then
' Converting text to double (it was done implicitely in your code, but it's better to understand what's happening to better control it)
Dim myNumber As Double = CDbl(TextBox1.Text) ' CDbl as in 'Convert DouBLe'
Dim maxNumber as Double = myNumber
' If the number is odd, we multiply by 3 and add 1
If myNumber Mod 2 = 1 Then
myNumber = (myNumber * 3) + 1
If myNumber > maxNumber Then maxNumber = myNumber
End If
' Let's count how many divisions before there's only 1 left
Dim i As Integer = 0
While (myNumber > 1)
myNumber = myNumber / 2
i += 1
End While
MessageBox.Show("It took " & i.ToString & " divisions until my number was reduced to 1. The max number was " & maxNumber.ToString & ".")
Else
' This will appear if you try to use non-numeric, like letters
MessageBox.Show("Use only numbers.")
End If
End Sub
Have fun!
Try something like this,
Dim number1 As Double
Dim maxNumber As Double = 0
Dim steps as Double = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
number1 = TextBox1.Text
MessageBox.Show($"Sayı {If( (number1 Mod 2) = 1, "tektir", "çifttir") }")
While number1 > 1
number1 = If((number1 Mod 2) = 1, number1 * 3 + 1, number1 * 2)
maxNumber = Math.Max(number1, maxNumber)
steps += 1
End While
MessageBox.Show($"Steps: {steps}{Environment.NewLine}Max number reached: {maxNumber}")
End Sub
You should write a proper loop in order to repeat this process until you reach 1. Moreover, it is better for you that if you get used to use & symbol instead of + symbol to concat strings.

visual basic: Enter some numbers until a negative value is entered to stop the program

private Sub Command1_Click()
a = InputBox("What is the Number ?", "Input Example"," ")
If a = "-1" Then
End If
End Sub
the whole question is: Enter some numbers until a negative value is entered to stop the program(stop running the what is your number thing). then find the average of the entered numbers.
What I want to do, for now, I want to know how can I make my "a" variable accept any negative value like in the code above it stops when I enter -1 but I want to stop when I enter -3, -10, or any negative value.
There are some helpful answers down below
If you are expecting the usual input to be text then you can use the Double.TryParse method to check if a number was entered. If it was, then you can check if that number is negative, and exit the application if so:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim userMsg As String
userMsg = Microsoft.VisualBasic.InputBox("What is your message?", "Message Entry Form", "Enter your message here", 500, 700)
If userMsg <> "" Then
Dim x As Double
If Double.TryParse(userMsg, x) AndAlso x < 0 Then
Application.Exit()
End If
MessageBox.Show(userMsg)
Else
MessageBox.Show("No Message")
End If
End Sub
The AndAlso operator only looks at the second argument if the first evaluated to True.
If you would like to repeat some portion of code till specific condition is met, you need to use:
While...End While Statement (Visual Basic)
or
Do...Loop Statement (Visual Basic)
It's also possible to write conditional loop using For... Next statement
Dim myNumber As Integer = 0
Dim mySum As Integer = 0
Dim myCounter As Integer = 0
Do
Dim answer As Object = InputBox("Enter integer value", "Getting average of integer values...", "")
'check if user clicked "Cancel" button
If answer <> "" Then
'is it a number?
If Int32.TryParse(answer, myNumber)
If myNumber >=0 Then
mySum += myNumber
myCounter += 1
Else
Exit Do
End If
End If
End If
Loop
Dim average As Double = mySum/myCounter
'you can display average now
Tip: Do not use InputBox, because this "control" is VisualBasic specific. Use custom Form instead. There's tons of examples on Google!

Automatic decimal places in textbox

It looks very strange, but I can't find an online solution for my problem! At least in VB.NET.
Here's the deal:
I have a TextBox in a form (limited to numbers by a KeyPress event) and want to keep two decimal places as long as the user inputs his data.
For example, if the TextBox is blank, then, when the user presses, let's say, "2", the TextBox shows "0,02". Then, if the user presses "7", the TextBox shows "0,27". Then again, by pressing "6", it shows "2,76" and so on...
I managed to do this for one decimal place with the code:
Select Case Me.TextBox.Text
Case ""
Case ","
Me.TextBox.Text = ""
Case Else
Me.TextBox.Text = Strings.Left(Replace(Me.TextBox.Text, ",", ""), Strings.Len(Replace(Me.TextBox.Text, ",", "")) - 1) & "," & Strings.Right(Replace(Me.TextBox.Text, ",", ""), 1)
Me.TextBox.SelectionStart = Len(Me.TextBox.Text)
End Select
Please note that: 1. This code's running on a TextChanged event; 2. I'm from Portugal and here we use a comma (",") instead of a dot (".") for the decimal separator.
Could you help me to adjust my piece of code to work properly with two decimal places?
Any help will be very appreciated. And, as always, thank you all in advance.
Here's a custom class I've made which does what you require:
Public Class FactorDecimal
Private _value As String = "0"
Public DecimalPlaces As Integer
Public Sub AppendNumber(ByVal Character As Char)
If Char.IsNumber(Character) = False Then Throw New ArgumentException("Input must be a valid numerical character!", "Character")
_value = (_value & Character).TrimStart("0"c)
End Sub
Public Sub RemoveRange(ByVal Index As Integer, ByVal Length As Integer)
If _value.Length >= Me.DecimalPlaces + 1 AndAlso _
Index + Length > _value.Length - Me.DecimalPlaces Then Length -= 1 'Exclude decimal point.
If Index + Length >= _value.Length Then Length = _value.Length - Index 'Out of range checking.
_value = _value.Remove(Index, Length)
If _value.Length = 0 Then _value = "0"
End Sub
Public Overrides Function ToString() As String
Dim Result As Decimal
If Decimal.TryParse(_value, Result) = True Then
'Divide Result by (10 ^ DecimalPlaces) in order to get the amount of decimal places we want.
'For example: 2 decimal places => Result / (10 ^ 2) = Result / 100 = x,xx.
Return (Result / (10 ^ Me.DecimalPlaces)).ToString("0." & New String("0"c, Me.DecimalPlaces))
End If
Return "<parse error>"
End Function
Public Sub New(ByVal DecimalPlaces As Integer)
If DecimalPlaces <= 0 Then DecimalPlaces = 1
Me.DecimalPlaces = DecimalPlaces
End Sub
End Class
It works by letting you append numbers to form a long string of numerical characters (for example 3174 + 8 = 31748), then when you call ToString() it does the following:
It parses the long number string into a decimal (ex. "31748" => 31748.0)
It divides the decimal by 10 raised to the power of the amount of decimals you want (for example: 2 decimals => 31748.0 / 102 = 317.48).
Finally it calls ToString() on the decimal with the format 0.x - where x is a repeating amount of zeros depending on how many decimals you want (ex. 2 decimals => 0.00).
NOTE: This solution adapts to the current system's culture settings and will therefore automatically use the decimal point defined in that culture. For example in an American (en-US) system it will use the dot: 317.48, whereas in a Swedish (sv-SE) or Portuguese (pt-PT) system it will use the comma: 317,48.
You can use it like this:
Dim FactorDecimal1 As New FactorDecimal(2)
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
If Char.IsNumber(e.KeyChar) = False Then
e.Handled = True 'Input was not a number.
Return
End If
FactorDecimal1.AppendNumber(e.KeyChar)
TextBox1.Text = FactorDecimal1.ToString()
End Sub
Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
Dim TargetTextBox As TextBox = DirectCast(sender, TextBox)
e.SuppressKeyPress = True
Select Case e.KeyData 'In order to not block some standard keyboard shortcuts (ignoring paste since the pasted text won't get verified).
Case Keys.Control Or Keys.C
TargetTextBox.Copy()
Case Keys.Control Or Keys.X
TargetTextBox.Cut()
Case Keys.Control Or Keys.A
TargetTextBox.SelectAll()
Case Keys.Back, Keys.Delete 'Backspace or DEL.
FactorDecimal1.RemoveRange(TextBox1.SelectionStart, If(TextBox1.SelectionLength = 0, 1, TextBox1.SelectionLength))
TextBox1.Text = FactorDecimal1.ToString()
Case Else
e.SuppressKeyPress = False 'Allow all other key presses to be passed on to the KeyPress event.
End Select
End Sub
Online test: http://ideone.com/fMcKJr
Hope this helps!
Thank you #Visual Vincent. Your method works fine. However I managed to find a simpler way of doing what I asked by the following code:
Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox.KeyPress
If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
End Sub
Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) Handles TextBox.TextChanged
Select Case Val(Replace(Me.TextBox.Text, ",", "."))
Case 0 : Me.TextBox.Text = ""
Case Else
Me.TextBox.Text = Format(Val(Replace(Me.TextBox.Text, ",", "")) / 100, "0.00")
Me.TextBox.SelectionStart = Len(Me.TextBox.Text)
End Select
End Sub
This piece of code look suspicious simple to me. For now it works fine and does the trick exactly how I wanted. Maybe there's something missing to me, or maybe I wasn't clear enough on the description of my goal.
If you find any flaw on my method, please feel free to point it! I'll appreciate it very much.

windows application in vb.net for calculating student marks

I need to make a vb.net windows application for calculating the student marks.I have three valuations.For example if valution1 is 45 marks and if valuation2 has 30 then there is 15 marks difference so valuation3 has to be done.Then average will be calculated by adding valuation 3 with maximum score of valuation1 and valuation2.valuation3 is done only when there is a difference of 15 or more marks in valuation1 and valuation2.Please help me to make this application as i am new to coding.
Get three textboxes, set the third textbox's enabled property to false. The following code will help you (under textbox's textchanged event).
Private Sub Hello () Handles Textbox1.Textchanged, Textbox2.Textchanged
If Val(Textbox1.Text) - Val(Textbox2.Text) >= 15 then
Textbox3.Enabled = True
Else
Textbox3.Enabled = False
End If
End Sub
For average, you need to add all the values and then divide by number of terms. Suppose you display the average in a label:
Dim a as integer
If Textbox3.Enabled = True then
a = Val(Textbox1.Text) + Val(Textbox2.Text) + Val(Textbox3.Text)
Label1.Text = a/3
Else
a = Val(Textbox1.Text) + Val(Textbox2.Text)
Label1.Text = a/2
End If
I hope you understand! This was a type of homework, but I did it just because I was bored. Please don't ask such questions in the future. Read the 'How to Ask' guide next time.

Random Generator in Loop

I am having some problems with an assignment. The case project is:
Create an application that allows the user to guess a random number generated by the computer. When the user makes an incorrect guess, the application should move an image either upr or down, depending on how the guess compares to the random number. If the random number is greater than the user's guess, the application should move the image up to indicate that the user needs to guess a higher number. If the random number is less than the user's guess, the application should move the image down to indicate that the user needs to guess a lower number. The game ends when the user guesses the random number. However, the application should allow the user to stop the game prematurely. When that happens the application should siplay the random number.
I have tried every which way I can think of including using a textbox instead of an inputbox and playing around with the syntax - but just can't seem to get it right. Advice would be much appreciated. Thanks.
My code:
Public Class Form1
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Me.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Number As Integer
Dim inputNumber As Integer
Dim answer As Integer
Dim isconverted As Boolean
Dim computerchoice As New Random
answer = computerchoice.Next(1, 20)
inputNumber = InputBox("Please guess number", "Random Number Game")
Do
isconverted = Integer.TryParse(inputNumber, Number)
If isconverted = True Then
If answer = Number Then
MessageBox.Show("You Win")
ElseIf answer > Number Then
PictureBox1.SetBounds(0, 90, 0, 0, BoundsSpecified.Y)
ElseIf answer < Number Then
PictureBox1.SetBounds(0, 220, 0, 0, BoundsSpecified.Y)
End If
Else
MessageBox.Show("Please enter a valid number between 1 - 20 only")
End If
inputNumber = InputBox("Please guess number", "Random Number Game")
Loop While answer <> Number
MessageBox.Show("Answer:" & answer.ToString)
End Sub
End Class
Your code actually almost worked. A few things though:
The only thing that really didn't work was the picture moving up and down. All you have to do for that is to increment/decrement the .Top property.
Because you converted your input to a number at the beginning of the loop and not evaluating till the end, you were looping through an extra time after you got the right answer.
The number comparison after the conversion was redundant, since you know they got the number if they exit the loop.
If you're new to Visual Studio and don't know about breakpoints and other debugging, it is worth it to look into those. With these tools you can pause your code at given points in your program, look at the values variables hold, and step through your code line-by-line.
Here's the working code:
Do
If isconverted = True And Number >= 1 And Number <= 20 Then
If answer > Number Then
PictureBox1.Top -= 10
ElseIf answer < Number Then
PictureBox1.Top += 10
End If
Else
MessageBox.Show("Please enter a valid number between 1 - 20 only")
End If
inputNumber = InputBox("Please guess number", "Random Number Game")
isconverted = Integer.TryParse(inputNumber, Number)
Loop While (answer <> Number)
MessageBox.Show("You Win! The answer is " & answer.ToString)