Decimals where they shouldn't be - vb.net

I nabbed a bit of code that prevents the user from entering non-numbers into a textbox, and monkeyed with it for a bit, trying to get it to include an exception for a decimal point. It didn't work, so I figured I'd just put the code back the way it was when I found it, because I don't yet know how to fix things if I break them.
Weird thing is, as soon as i put the code back to normal it suddenly started doing the thing I originally wanted it to, namely allowing the user to type a decimal into the textbox. This would be righteously excellent, if I could understand why in the name of Shiva my tiny program is doing something that it isn't programmed to do.
Have I somehow given birth to true AI and started the singularity?
EDIT (for clarity):
I am a total beginner.
I found this code that only allows numbers,
backspace, and delete to be added to a textbox.
I altered it, making assumptions about what it was doing, so that it would also allow a decimal point.
This didn't work.
I returned the code to how I found it.
Only after this point did it start allowing the decimal point.
This doesn't make sense, because it is now doing something that isn't in the code.
Does the same thing happen to you when you put the code into Visual Studio?
If so, why might this be happening?
Is the world going to end because my computer is interpreting my desires and performing them in spite of all of the rules of space, time, and logic?
Public Class Form1
Private Sub TextBox3_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox3.KeyPress
If Not Char.IsNumber(e.KeyChar) And Not e.KeyChar = Chr(Keys.Back) And Not e.KeyChar = Chr(Keys.Delete) Then
e.Handled = True
MessageBox.Show("numbers only", "baleted")
End If
End Sub
End Class

I miss-understood your question. I did a little rework on it. My bad!
Private Sub TextBox2_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox2.KeyPress
If (e.KeyChar = "." OrElse e.KeyChar = Chr(Keys.Back) OrElse IsNumeric(e.KeyChar)) Then
e.Handled = False
Else
e.Handled = True
End If
End Sub
Not the prettiest thing I've ever barfed out, but basically this will check if the key pressed is a Decimal or a back space and allow those, I showed two different ways you can compare e.KeyChar in my code. If it isn't either on of those keys it will check if its a number using IsNumeric. If it's none of those things it will ignore it. Not my best work, but you can build upon this, make it your own, make prettier.
e.Keychar is information that is gathered when the keypress event happens. You can use the e.KeyChar to compare any button pressed on the keyboard and basically customize your textbox per keystroke. I hope this can get you started on the right path.
All else fails, search for key terms you find in code like e.KeyChar there is a ton of information out there.
Microsoft usually does a pretty decant job of explaining thing like e.KeyChar and e.Handled.
Best of luck!

Related

Prevent the introduction of similar characters vb.net

Is it possible to prevent entering characters that are already in the textbox?
like if I wrote in textbox
abcd
Then it is not allowed to write the same letters in it,
I searched and tried but could not find a way
All are about stopping letter gouging
It's pretty simple, just use the following code:
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
e.Handled = TextBox1.Text.Contains(e.KeyChar)
End Sub
It'll help preventing typing the existing text(s) containing in a TextBox.
Hope it helps you!

Textbox and currency formatting

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.

Issue with making terminal

I am coding a terminal in VB.net, And when I type in 'help' and press enter, Nothing happens. It is supposed to show 'This is the only command. :P'.
I appear to not be more specific so let me explain what happened.
I put in the code below, I executed the application and then I typed in 'help' and then I hit the enter key then nothing happened at ALL.
Here is the entire code:
Private Sub RichTextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles RichTextBox1.KeyPress
Dim lines = RichTextBox1.Lines
Dim num = lines
Dim textlength = RichTextBox1.TextLength
If Asc(e.KeyChar) = 13 Then
If num.Last.ToString() = "help" Then
RichTextBox1.AppendText("This is the only command. :P\r\n")
End If
End If
End Sub
Please help!
So, having attached a debugger to your code, it was instantly obvious what the problem is... When you get to the comparison, lines.Last() is an empty string.
There are a number of ways to get the 2nd to last line. I prefer LINQ, so here's your code tidied up, using a case and culture-insensitive string comparison (so you can type Help too)...
Private Sub RichTextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles RichTextBox1.KeyPress
If Asc(e.KeyChar) = 13 Then
If String.Equals(RichTextBox1.Lines.Reverse.Skip(1).First(),
"help",
StringComparison.InvariantCultureIgnoreCase) Then
RichTextBox1.AppendText(String.Format("This is the only command. :P{0}", Environment.NewLine))
End If
End If
End Sub
I've also used Environment.NewLine to make your code more portable, and String.Format() to combine the strings in a way that doesn't eat memory for no reason. It's overkill for this example but it shows how it should be done.
It's worth noting that using a debugger is a crucial skill for any developer (well, ok, there is an alternative which is extensive logging, but you need to know both). You will need this skill to solve any number of problems.
In case you're not familiar with the concept, debugging is like pausing your program and letting you examine what's going on, then run a single command at a time to see what the program is doing.
This isn't really an answer, but I noticed that you are writing your code to create a new line incorrectly
You did this:
RichTextBox1.AppendText("This is the only command. :P\r\n")
While it should be something like this:
RichTextBox1.AppendText("This is the only command. :P" & vbCrLf)
By trying your code and removing the
If num.Last.ToString() = "help" Then
End If
And putting this line of code
If Asc(e.KeyChar) = 13 Then
RichTextBox1.AppendText(Environment.NewLine & "This text will appear on the next line.")
End If
It works fine.
Hope this helps.

How to make `KeyDown` and `KeyUp` ignore modifier keys and how to print the key to a string in Visual Basic

In VB, I usually put my code for when keys are pressed in the KeyDown and KeyUp subs. However, I would prefer it if this code could be put in the Timer_Tick.
So I implemented the method shown below in the code where the program creates a List (Of Keys) upon starting, and then the KeyDown and KeyUp subs adds or removes the Keys from the List.
To debug, the program draws a string of all of the Keys in the Paint sub which is refreshed every frame.
This method of handling key presses works fine mostly, except for the following problems I've encountered:
keysPressed(i).ToString doesn't draw , or any non-letter characters as I would expect it to. Instead, it draws Oemcomma. Is there a way to fix this? (I know it's not important for now as it's just a debugging feature, but I would still like to know how to get around this for the future)
The modifier keys are a nuisance for me. After being pressed, the KeyUp sub isn't called once released (I suspect this is because they modify themselves) and some keys aren't detected at all (like fn).
In addition, if I were to press and hold A, then press Shift and then release A, then KeyUp for A isn't called (as it has been modified) which means that Keys.A is not removed from my list. I would like KeyUp for A to be called whether or not A has been modified.
Is there a way to tell VB to ignore all modifier keys in the KeyDown and KeyUp subs? (here I mean ignore as in ignore all modifications, despite still being able to detect the modifier key being pressed)
When I press a load of buttons (over 10), then it seems that they are not all detected at once (only 6 or so appear in the list). Is there a way to avoid this bug, or is this a limitation of using VB?
In fact, occasionally, when I press a few more buttons whilst holding another one, the one I was holding seems to be 'cancelled out' by being removed from the list until I release. (There are quite a few bugs which appear when I press a lot of keys).
When I press multiple keys down at the same time, what exactly happens? Is KeyDown called multiple times for each key, or is it actually possible for a KeyDown to represent multiple keys? In which case, what exactly would happen in my program?
Public Class Form1
Dim keysPressed As New List(Of Keys)
Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If Not keysPressed.Contains(e.KeyData) Then keysPressed.Add(e.KeyData)
If e.KeyData = Keys.Escape Then End
End Sub
Private Sub Form1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
keysPressed.Remove(e.KeyData)
End Sub
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles screenTimer.Tick
Refresh()
End Sub
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
For i = 0 To keysPressed.Count - 1
e.Graphics.DrawString(keysPressed(i).ToString, New System.Drawing.Font("Arial", 10), Brushes.Black, 10 * i, 540)
Next
End Sub
End Class
No, code it yourself. It's great the way it is for your purposes functionality-wise, and debugging wise, I prefer it that way, so maybe you should take my advice and not fight it. Consider looking at a trace of all the keystrokes and seeing , mixed in with a bunch of otherwise sensible seeming key names. Imagine Ctrl+, and etc. (when making this code you really need to debug or console trace every event)
So rip apart the keydata by taking out the modifiers. There isn't a way to change the way the keydatas come to you. It's inconvenient for some purposes, but useful for some others.
It's your keyboard's fault. In general you can't press many keys at once. It has nothing to do with VB or .net
Precisely what you expect happens; one keydown can only represent one key. If you can even find a way to store information about more than one key inside the KeyEventArgs, then you're a magician
Despite not using winforms events, the code here does what you're attempting: https://github.com/TASVideos/BizHawk/tree/master/BizHawk.Client.EmuHawk/Input ; It receives key events in bunches, but processing them is more or less the same as if they came from winforms. But believe it or not, we actually have to go to effort to reconstruct the way winforms delivers them with the modifiers combined with the keystrokes (see point #2)--not because of compatibility with old winforms code, but because that's the way we prefer it.

Lost Focus problems

I use the LostFocus Event in vb.net to check the validity of a field for the name.
After this field a have another one which is the for the password validity, and i'm handilg the same event in order to check the password.
My problem comes when i run the (name) lost focus, runs the code inside the sub and after that automatically goes to the password_lostfocus which brings me alot of troubles.
That happens even i use the error provider which works fine and bring to me the error with the red flashing.After that i put the command (name_textbox.focus), which logically has to bring the control in the name_textbox.. But NO.. the control goes to the Password_textbox sub automatically.
Please see my sub
Private Sub UsernameTextBox_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles UsernameTextBox.LostFocus
Select Case DB_Access.IfExistUser(UsernameTextBox.Text, sender, e)
Case True
PasswordTextBox.Focus()
Case False
ErrorProvider1.SetError(UsernameTextBox, "Ο χρήστης ΔΕΝ υπάρχει παρακαλώ καλέστε τον Administrator")
Beep()
UsernameTextBox.Text = ""
UsernameTextBox.Focus()
End Select
End Sub
Please if anyone have seen this issue and face it, assist me.
Excuse me for some Greek characters they are meaningless, they are comments
Well finally i found that.
In order to handle the Login Form as it give it from visual studio 2010 you need to do it in only one sub (Lost Focus) and that is only the password_LostFocus.
I believe the particular form is meant to be like that.
Any way i solve the issue and if anybody needs assistance on that just "asc a question"