Issue with making terminal - vb.net

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.

Related

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.

Decimals where they shouldn't be

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!

Referring To MessageBox VB.NET

I'm writing a program that kids can use to code from within my application instead of a console-based approach
So I have a lesson that teaches them about message boxes, they are given a sample line of code and what it creates and are told to create their own by entering code into a textbox to create their own that says "Hey Dude!", the problem is, I'm having trouble getting the system to check if what they entered was correct or not... eg:
Private Sub btnShowMsgBox_Click(sender As Object, e As EventArgs) Handles btnShowMsgBox.Click
If txtUserInput.Text = MessageBox.Show("I can code!") Then
MessageBox.Show("I can code!")
Else
MessageBox.Show("That's not quite right, try again!")
End If
I've tried adding " " around the relevent code on the first line of the if statement but no joy, as well as trying a variable approach
So basically the problem is the program is getting confused and doesn't understand why I'm checking to see if code for a message box is present, the syntax of the messagebox code doesn't fit well either
Does anyone have any suggestions as to how I would get this working? The logic is so straightforward but it's driving me nuts!
Thanks a million in advance
I believe you want the code to look more like...
Private Sub btnShowMsgBox_Click(sender As Object, e As EventArgs) Handles btnShowMsgBox.Click
If txtUserInput.Text = "MessageBox.Show(""I can code!"")" Then
MessageBox.Show("I can code!")
Else
MessageBox.Show("That's not quite right, try again!")
End If
The double quotes will return as single quotes within the string between the single quotes.

Decimal.TryParse is failing on TextBox.Leave and TextBox.LostFocus

This has got to be one of the most frustratingly stupid bugs I have ever encountered, and I just want to see if anybody else has run into this before.
Here's the deal. I have a TextBox in a Windows Forms application in VB 2008 (.NET 3.5) where a user can key an estimate amount. I am allowing them to key dollars and cents, and I want to round to the nearest dollar. The original code had the rounding down when the data was written back to a table, and that worked fine - I have this code in a "Save" routine that fires when the user moves to a different screen or record:
Dim est As Decimal : Decimal.TryParse(txtEstimateAmount.Text.Trim, est)
Dim estimatedAmount As Integer = Math.Round(est)
I decided that it might be nice to actually do the rounding as soon as they leave the field instead, so they're not surprised when they reload the screen and find that 1822.60 is now 1823. So I took the exact same code and added it to the TextBox.Leave event handler. And the weirdest thing happened: instead of the variable est being populated with 1822.60 after the parse, it gets set to -1! What the...?
Debugging the handler shows that the value goes into the parser correctly, and if I do the parsing manually via the Immediate window, it parses correctly, but when I let the code do it, it invariably gets set to -1. What's even weirder is that any number gets parsed as -1, not just decimals, and any non-number gets parsed as 0 (which is correct).
Has anybody else ever run into this before? I tried moving the code to the TextBox.LostFocus event instead, but with the same results. I have no idea what in the heck is going on, and obviously there are workarounds galore for this, but it just makes no sense whatsoever.
EDIT: Here's the full event handler (current behavior for which is to put -1 in the TextBox):
Private Sub txtEstimateAmount_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtEstimateAmount.Leave
' Take any dollars-and-cents amount and round to the nearest dollar
Dim est As Decimal
est = Decimal.TryParse(txtEstimateAmount.Text.Trim, est)
txtEstimateAmount.Text = If(est <> 0, Math.Round(est).ToString(), String.Empty)
End Sub
First off, you really need to do this with a Validating event handler so that you can catch junk and avoid ignoring the return value of TryParse. Like this:
Private Sub TextBox1_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
Dim est As Decimal
If TextBox1.Text.Length = 0 then Exit Sub '' optional
If Not Decimal.TryParse(TextBox1.Text.Trim, est) Then
e.Cancel = True
TextBox1.SelectAll()
Else
TextBox1.Text = est.ToString("N0")
End If
End Sub
Explaining -1 is difficult. TryParse normally writes 0 if it cannot parse the text. Watch out for changing the UI thread's CurrentCulture property. And any changes made to the format settings in Control Panel + Region and Language applet.
I don't think the code you've posted is the code you're running. What is happening is:
Dim est As Decimal = Decimal.TryParse(txtEstimateAmount.Text.Trim, est)
Dim estimatedAmount As Integer = Math.Round(est)
I would do a clean and a rebuild or try rewriting it in a different format, maybe with a boolean to get the result of the tryparse.
EDIT now that I've seen your actual code. You are indeed putting the true/false from the tryparse result into the est decimal. Delete the est=. Est gets loaded because it is passed by reference into tryparse.

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"