Simplify one-type syntaxis in vb.net - 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).

Related

Needing Assistance with vb.NET Application

I don't normally post on forums because I try to find information for myself, and ask as an absolute last resort. I've tried scouring the net for answers, but I'm only receiving about half of the answer I'm looking for.
I'm currently building an application that deals with state law. There's one combo box and one text box. One for the offense title, and one for the numerical code for that particular code section. So say if I select "Kidnapping", it prepopulates the text box below it with "11-5-77", for example.
The method I've been using for, oh, about the last hour now, is:
If AWOffenseTitle.Text = "Kidnapping" Then
AWCN.Text = "11-5-77"
ElseIf AWOffenseTitle.Text = "False Imprisonment" Then
AWCN.Text = "11-5-78"
With AWOffenseTitle being the combo box name, and AWCN being the text box name. While this has proved to work perfectly well so far, I'm sure you can imagine with hundreds of offense titles, this is going to take a ridiculously long time. Well, I finally found a spreadsheet with offense titles and their respective title codes. What I'm looking to do is create two text files within a folder in the local directory "Offenses". One with a vertical list of offenses, and one with a vertical list of offense code numbers that populate the same lines in each. What I'm looking to do is populate the combo box with the contents of text file one (which I can do already), but then selecting an offense title will read the second text file and display it's proper title code. That's what has me at a loss. I'm relatively well-versed with vb.NET, but I'm not an expert by any means.
I'm hoping someone here will be able to provide a code example and explain it to me line-by-line so I can gain a better understanding. I want to get more proficient with VB although it's not so popular anymore. I've been using VB since 6.0, but not on a regular basis. More on a sporadic project kind of basis.
I really appreciate any assistance anyone might be able to provide, and if you need more information, I'd be glad to answer any questions. I tried to be as thorough as I could.
Thank you in advance!
First, you need to retrieve your data. I demonstrated using an Sql Server database containing a table named Offenses with columns named OffenseTitle and OffenseCode. You will have to change this code to match your situation.
Private Function GetOffenseData() As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("Select OffenseTitle, OffenseCode From Offenses;")
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
As the Form loads, set the properties of the ComboBox. DisplayMember matches the name of the title column and ValueMember is the name of the code column.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetOffenseData()
ComboBox1.DisplayMember = "OffenseTitle"
ComboBox1.ValueMember = "OffenseCode"
ComboBox1.DataSource = dt
End Sub
Then when the selected item in the combo changes, just set the .Text property of TextBox to the SelectedValue in the combo and your code appears.
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
TextBox1.Text = ComboBox1.SelectedValue.ToString
End Sub
There are other ways to do this if your data source is other than a database. Please advise if you need additional help.
In addition to HardCode's comment and Mary's detailed answer, I can only add an answer that's somewhere in between them.
It might be the case, that the information is not taken from a database, but from another source, like a text/data file or a web service. So it might be useful to create an abstraction for the data source you actually use.
First, I create a class or struct that will hold the data for each combo box item.
Class Offense
Public ReadOnly Property Title As String
Public ReadOnly Property Code As String
Public Sub New(title As String, code As String)
Me.Title = title
Me.Code = code
End Sub
End Class
Next, you need a method that retrieves a list of offenses that you can bind to your combo box. It's entirely up to you how you fill/fetch the offenses list. I have simply hard coded your two values here.
Private Function GetOffenseData() As List(Of Offense)
Dim offenses As New List(Of Offense)
offenses.Add(New Offense("Kidnapping", "11-5-77"))
offenses.Add(New Offense("False Imprisonment", "11-5-78"))
Return offenses
End Function
At a certain moment (probably in your form's Load event handler), you need to initialize your combo box. Just like Mary did, I use data binding.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AWOffenseTitle.DropDownStyle = ComboBoxStyle.DropDownList
AWCN.ReadOnly = True
AWOffenseTitle.DisplayMember = NameOf(Offense.Title)
AWOffenseTitle.ValueMember = NameOf(Offense.Code)
AWOffenseTitle.DataSource = GetOffenseData()
End Sub
Note that I use the NameOf operator to get the desired property names of the Offense class. If you ever decide to rename the properties of your Offense class, you will be able to easily detect where they are used, since the compiler will complain if your code still uses the wrong property names somewhere.
Finally, the app needs to react to combo box value changes, so that the text box will show the corresponding offense code. Mary used an event handler for the SelectionChangeCommitted event, but I use a handler for the SelectedIndexChanged event instead:
Private Sub AWOffenseTitle_SelectedIndexChanged(sender As Object, e As EventArgs) Handles AWOffenseTitle.SelectedIndexChanged
AWCN.Text = AWOffenseTitle.SelectedValue
End Sub
(Up to now, I was not aware of the SelectionChangeCommitted event of the ComboBox control. I will need to look into this event to see if it is actually a better choice for this scenario, but I found that the SelectedIndexChanged event does the job just fine, so for now I sticked with that event, since I am more familiar with it.)

VB.NET Check for keydown on dragdrop

I've tried searching quite a bit for this answer but haven't been able to find a good solution.
I have a datagridview on my form where users can drag and drop files onto the grid and certain columns are filled in. This works fine.
I want to be able to check if a user has a certain key pressed at the time the file is dropped. If so, I want to use that to add specific data to one of the columns in the datagrid.
Is this possible?
EDIT:
I have used keydown outside of dragdrop before but it seems that I'm missing something. The code I have is below. No matter what I do, I never get "T is pressed" but I always get "T is not pressed".
Private Sub frmReader_DragDrop(sender As Object, e As DragEventArgs) Handles Me.DragDrop
Dim files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
If Keyboard.IsKeyDown(Keys.T) Then
MsgBox("T is pressed.")
' Put certain info into the datagridview
Else
MsgBox("T is not pressed.")
' Put other data into the datagridview
End If
End Sub
God, embarassing... I changed "Keys.T" to "Key.T" and it's working fine. Sorry for the bother.

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 can i do arithmetic operations in one TextBox?

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.

How do I pass Form1.TextBox1.Text to Form2.TextBox2.Text using Visual Basic (correctly)?

This is a continuation of a question asked two years ago in this thread:
VB6 equivalent of string.IsNullOrEmpty
(I think.) A programmer recommended I use the String.IsNullorEmpty method, which I used this thread for to convert to Visual Basic, but I still couldn't get it to work.
The specifics of my question are here, including all current code:
http://www.daniweb.com/software-development/visual-basic-4-5-6/threads/473930/passing-data-between-forms-in-vba
Here is the gist of it, copied directly from the second link:
So I'm trying to make a link between TextBox1.Text on Form1 to TextBox2.Text on Form 2. What I currently have is a line of code underneath my TextBox2_Change code reading:
TextBox2 = Form1.TextBox1.Text
This ALMOST does what I want it to do. The only problem is that it is requiring me to input any character in to the TextBox2 when Form2 pops up before it displays.
I'm trying to get that problem solved and then I'm eventually going to try to get it to chop off part of the file name until just the project file name displays.......but that's a whole different game I'll be playing. One step at a time.
Does anyone have any suggestions?
Explanation
You should write the code under the Form2_Load event.
If you write the code under Textbox2_TextChanged event, the code will be executed only when you type or delete something in Textbox2 (That is the same as Text being changed).
Code and Example
Private Sub Form2_Load () Handles Mybase.Load
Textbox2.Text = Form1.Textbox1.Text
End Sub
Hope it works perfectly!
The behaviour you observe is normal : your TextBox2 is only updated (with the value from TextBox1) ... when you update it manually (_Change).
Hey friend it very simple. you need not to add any kind of other functions just use dot(.) operator to access all components of Form1.
e.g.:
Form1.TextBox1.AppendText("hello")
or you can read value from Form2 and insert it into Form1.
e.g. :
Dim txt As String=TextBox1.Text
Form1.TextBox1.AppendText(txt)