How can i do arithmetic operations in one TextBox? - vb.net

For example i write in TextBox1
4*5 or 3-2
how can make the answer appear in the same textbox ?
I tried this but it did not work anyway
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
textbox1.text = val(textbox1.text)
end sub
it just shows the first number

This is a rather complex task for which there is no built-in support in the VB.NET language. The first step is to parse the text into an expression tree. The second step is to evaluate that expression tree to determine the result. The task is certainly an advanced one for beginners, but rather than doing it yourself, there are a couple other options. You could use an existing third-party library which does all of the heavy lifting for you, such as the free open-source NCalc library. Or, you could use .NET's CodeDom classes to dynamically build the expression as a .NET library and then call it to get the result.

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.

How do I find and open the most recent txt file within a subdirectory structure using vb.net

Using vb.net I am writing a standalone application that needs to read a value from the very latest text file written to a random subdirectory from a known directory. I need this to run on a scheduled basis so I am using the vb timer.
Despite searching the web for some time I can't seem to find any code to perform this relatively simple task without visual studio failing to compile all the examples I've tried. Surely this is quite a simple task?
Also what would be the most efficient way of doing this?
Private Sub tmrLoop_Tick(sender As Object, e As EventArgs) Handles tmrLoop.Tick
For Each TXTFile As System.IO.FileInfo In New System.IO.DirectoryInfo(Server.MapPath("\\10.179.221.125\cmsdata\GNH3D\TDD\TDD_waveradar\H1d3\"))
.GetFileSystemInfos("*.txt", System.IO.SearchOption.AllDirectories)
.OrderByDescending(Function(f) f.LastWriteTimeUTC)
.Skip(PageSize * Page)
.Take(PageSize)
MsgBox(TXTFile)
Next
End Sub
The above code doesn't like the Server.MapPath part

Saving Database issue

So basically, I believe I am using the correct code yet the database will still not update. It will work for the current session, however, when I stop and restart the program, it appears that the data has not been updated in the database.
The really interesting part is that I am using the same method to update the database elsewhere, which when used and session restarted, the database has been updated.
p.s. I also have the same adapters and binding sources set up etc on both forms
I am so confused, help pls
Code that I believe is correct but is not working: (updating on another form so I have one place where all forms update hence FRMMain. etc)
Private Sub btnConfirm_Click(sender As Object, e As EventArgs) Handles btnConfirm.Click
Dim CurrentPoints As Integer
Dim UpdatedPoints As Integer
CurrentPoints = FRMMain.MyDBDataSet.Tables("TBLPupil").Rows(looopcount)(15)
UpdatedPoints = CurrentPoints + stfPoints
FRMMain.MyDBDataSet.Tables("TBLPupil").Rows(looopcount)(15) = UpdatedPoints
FRMMain.TBLPupilTableAdapter.Update(MyDBDataSet.TBLPupil)
FRMMain.TBLPupilTableAdapter.Fill(MyDBDataSet.TBLPupil)
End Sub
Code that I am using in another form that that DOES work:
Private Sub BtnYes_Click(sender As Object, e As EventArgs) Handles BtnYes.Click
Dim Points As Integer = FRMPupil.Pointss
Dim Cost As Integer = FRMPupil.RewardCost
Points = Points - Cost
FRMPupil.LePoints = Points
MyDBDataSet.Tables("TBLPupil").Rows(FRMLogin.DBLocation)(15) = Points
FRMMain.TBLPupilTableAdapter.Update(MyDBDataSet.TBLPupil)
FRMMain.TBLPupilTableAdapter.Fill(MyDBDataSet.TBLPupil)
Me.Hide()
End Sub
My code is correct but is not working.
No, if it is not working, then it is not correct!
There are different things you can do: DRY, Dont Repeat Yourself. You are repeating the code for updating points at several places in your code. This is error prone. Write it once and re-use it, e.g. by applying the the Repository Pattern. It makes it easier to detect errors and correct them. It allows you to re-use code that has already been tested in other scenarios (on another form).
Debug, debug, debug. Place breakpoints in the not working methods and see what happens. Do all the variables have the expected values? E.g., does looopcount have the same value as FRMLogin.DBLocation? There must be a difference somewhere. See: Navigating through Code with the Debugger or the more recent article Debug your Hello World application with Visual Studio 2017.

Simplify one-type syntaxis in vb.net

I have the next piece of code:
Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged,
TextBox3.TextChanged, TextBox4.TextChanged, TextBox5.TextChanged, TextBox6.TextChanged, TextBox7.TextChanged,
TextBox8.TextChanged, TextBox9.TextChanged, TextBox10.TextChanged, TextBox13.TextChanged, TextBox14.TextChanged,
TextBox15.TextChanged, TextBox18.TextChanged, TextBox19.TextChanged, TextBox20.TextChanged
Double.TryParse(TextBox1.Text, Component.Methane.Mole)
Double.TryParse(TextBox2.Text, Component.Ethane.Mole)
Double.TryParse(TextBox3.Text, Component.Propane.Mole)
Double.TryParse(TextBox4.Text, Component.iButane.Mole)
Double.TryParse(TextBox5.Text, Component.nButane.Mole)
Double.TryParse(TextBox6.Text, Component.neoPentane.Mole)
Double.TryParse(TextBox7.Text, Component.nHexane.Mole)
Double.TryParse(TextBox8.Text, Component.nHeptane.Mole)
Double.TryParse(TextBox9.Text, Component.N2.Mole)
Double.TryParse(TextBox10.Text, Component.CO2.Mole)
Double.TryParse(TextBox13.Text, Component.iPentane.Mole)
Double.TryParse(TextBox14.Text, Component.nPentane.Mole)
Double.TryParse(TextBox15.Text, Compress.Avol)
Double.TryParse(TextBox18.Text, Compress.AF)
Double.TryParse(TextBox19.Text, Compress.AP)
Double.TryParse(TextBox20.Text, Compress.AT)
End Sub
Is there any possibility to make this procedure more compact, beatiful and smarter ? Use some kind of control, loop or something else? It would be greate to make it shorter and avoid typing. I am quite new in programming, any help is very appreciated!
Thanks in advance!
If your range of textboxes should only contain numbers, create a new Control that inherits from Textbox and alter the Textbox to only accept valid numbers. See an example here:
https://www.tigraine.at/2008/10/28/decimaltextbox-for-windows-forms/
The other thing I would point you is to look into Databinding. Databinding is something where a WinForm or WPF Control will "push" the value contained within the Control back to a property on an object. Windows has made a nice and quick write up on it here:
https://msdn.microsoft.com/en-us/library/2b4be09b.aspx
Finally, for "beautiful code" give things meaningful names. Currently your textbox have the default name and this can result in some very confusing problems later on in life. A quick and easy naming convention I follow is , for example, instead of "TextBox15" you could have TextboxCompressAvol (Or, txbxCompressAvol).

How can I check if a string given is a real word?

I am making a program that solves anagrams in Visual Basic. How can I check if a string given by the anagram solver is a real word? I know I will have to access some sort of dictionary but I have no idea how to do this?
I need a function that checks the word to return a true/false boolean value. Is this possible?
I'm using Visual Basic in Microsoft's VS2015.
Hunspell is pretty easy to use.
Install the .net-library through Nuget (open your project in Visual Studio, then > Extras > Nuget-Package-Manager -> Console, type Install-Package NHunspell)
Download the .aiff and .dic files, see the dictionaries link on the Hunspell project page. Include these files in your project or use absolute paths.
Sample Code:
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Using h As New NHunspell.Hunspell(
"...path ...\en_US.aff",
"...path ...\en_US.dic")
Me.TextBox1.BackColor = If(h.Spell(Me.TextBox1.Text),
Color.PaleGreen, Color.PeachPuff)
End Using
End Sub
Hunspell
.net library NHunspell
NHunspell C# Code Samples
If your are using WPF then checking if a word in a textbox can be done simply by checking if it has a spelling error.
Public Function WordOk(Word As String) As Boolean
return TextBox1.GetNextSpellingErrorCharacterIndex(0, Windows.Documents.LogicalDirection.Forward) < 0
End Function
If you are using windows forms then you can create a "User Control (WPF)" to do the same thing, though it is a bit tricky to explain how to do that here.
(There may be a better test than the one I showed though.. I'm not overly familiar with WPF)