How can I make it so a TextBox will dynamically adjust the input as a currency format? - vb.net

This app I'm designing has a TextBox named txtValue with the properties MaxLength set to 14 and TextAlign set to Right. I want txtValue to only accept currency, and dynamically format the input so the user doesn't need to add commas, only one period.
I managed to make it so txtValue will only accept numbers and one dot in the event txtValue_KeyPress.
txtValue_LostFocus will convert the input into currency format.
Here's my code so far:
Private Sub txtValue_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtValue.KeyPress
'Allows only one dot
If (e.KeyChar.ToString = ".") And (txtValue.Text.Contains(e.KeyChar.ToString)) Then
e.Handled = True
Exit Sub
End If
'Allows only 0 to 9 and dot (once)
If (e.KeyChar.ToString < "0" OrElse e.KeyChar.ToString > "9") _
AndAlso e.KeyChar <> ControlChars.Back _
AndAlso e.KeyChar.ToString <> "." Then
e.Handled = True
End If
End Sub
Private Sub txtValue_LostFocus(sender As Object, e As EventArgs) Handles txtValue.LostFocus
txtValue.Text = Format(Val(txtValue.Text), "000,000,000.00")
End Sub
I expect the input -q1w23456789012....34 to return the output 123,456,789,012.34, but the actual output after it loses focus is 123,456,789,012.30
This seems like an easy fix, like setting MaxLength to 15, but then if I don't type a period, it'll allow me to type 15 numbers and I only want up to 12 plus 2 after the period.
I expect the input -q1w234....5678 to return the output 1,234.56, but the actual output after it loses focus is 000,000,001,234.56
This seems like a more complex fix, because I don't want to use the LostFocus event to validate what I type. I want the KeyPress event to handle the input and dynamically format what I type.
In this case:
The input 1 would have the output 1.00
The input 123.4 would have the output 123.40
The input 1234.567 would have the output 1,234.56
All of this without needing the LostFocus event, but right now I'm using the LostFocus event because that's all my very limited knowledge allows me to do.
UPDATE
Alright I'm now using the Leave event, but then again I was only using LostFocus as a placeholder because in the end I want the TextBox to adjust what the user types as they type.

An alternative way to handle. For details on formating numbers for display try MS docs https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings or https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings
Private err As New ErrorProvider()
Private d As Decimal 'In case you want to use the value as a number somewhere else
Private Sub TextBox17_Validating(sender As Object, e As CancelEventArgs) Handles TextBox17.Validating
If Not Decimal.TryParse(TextBox17.Text, d) Then
e.Cancel = True
err.SetError(TextBox17, "This text box must contain a number.")
Else
err.Clear()
End If
End Sub
Private Sub TextBox17_Validated(sender As Object, e As EventArgs) Handles TextBox17.Validated
TextBox17.Text = d.ToString("C")
End Sub

Related

How do I get the textbox to enable after a certain amount of text is inputted?

So my next question(i know i know ive had a lot of questions already but im learning and my teachers suck)
but I am trying to get the textbox to go to readonly after a certain amount of text has been entered. I know how to make it a read only textbox but only after Ive had one set of data entered. i need it to be readonly after 7 days of data has been entered
I've tried inputtextbox.enabled = false
'Validating if user input is a number or not
Dim output As Integer
If Not Integer.TryParse(InputTextbox.Text, output) Then
MessageBox.Show("ERROR! Data must be a number")
InputTextbox.Text = String.Empty
Else
UnitsTextbox.AppendText(Environment.NewLine & InputTextbox.Text)
InputTextbox.Text = String.Empty
End If
InputTextbox.Enabled = False
I'm expecting it to disable after the user has entered 7 days worth of data but it only disables after one day of data is entered
Since the entries to UnitsTextbox are all done in code, this TextBox can be set to read only at design time.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim output As Integer
If Not Integer.TryParse(InputTextbox.Text, output) Then
MessageBox.Show("ERROR! Data must be a number")
Else
UnitsTextbox.AppendText(Environment.NewLine & InputTextbox.Text)
End If
'Moved this line outside of the If because it happens either way
InputTextbox.Text = String.Empty
If UnitsTextbox.Lines.Length >= 7 Then
Button2.Enabled = False
End If
End Sub
Here's some simple psuedocode
Private Sub InvalidateTextbox(sender As TextBox, e As KeyEventArgs) Handles TextBox1.KeyUp, TextBox2.KeyUp
'FOR ANY TEXTBOX YOU WANT TO CONTROL WITH THIS SUB, ADD AN ADDITIONAL HANDLE.
If Strings.Len(sender.Text) > 7 Then
'^SIMPLE CONDITIONAL, CHECKING IF THE LENGTH IS MORE THAN SEVEN CHARACTERS, MODIFY THIS TO SUIT YOUR NEEDS.
sender.Enabled = False
'^IF THE CONDITIONAL IS TRUE, DEACTIVATE THE CONTROL, IF THAT IS WHAT YOU ARE LOOKING FOR.
sender.ReadOnly = true
'^IF YOU WANT READONLY,NOT ENABLED/DISABLED.
End If
End Sub
This code will execute every time a key is pressed while the text boxes are active. What is after "Handles" defines what events will trigger the sub.
sender becomes the textbox object that triggered the sub. e holds all the event arguments for the keyboard, so you can evaluate things like which key was pressed and other neat things.
There was some confusion on if you wanted enabled/disabled or readonly, both options included.

Textbox only converter

I am making a temperature converter in vb.net for my assignment. I know the conversion method and so on.. but the problem is, I need to only use two textboxes. One for Celsius and one for farenheit. Whenever I update the textbox for celsius, the changes on textbox should also happen, and when I change the value for farenheit, the celsius textbox should also change depending on the value for farenheit. What method should I do?
This is the current one im working on..
Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If TextBox1.Focus() Then
TextBox2.Clear()
TextBox2.Text = (TextBox1.Text - 32) / 1.8
ElseIf TextBox2.Focus() Then
TextBox1.Clear()
TextBox1.Text = (TextBox2.Text * 1.8) + 32
End If
End Sub
End Class
Thanks for posting some code. This is the way I'd do it (after wiring up TextChanged event handlers for both text boxes):
Private DegreesCChanging As Boolean = False
Private DegreesFChanging As Boolean = False
Private Sub DegreesF_TextChanged(sender As Object, e As EventArgs) Handles DegreesF.TextChanged
If Not DegreesFChanging Then
Dim Temperature As Double
DegreesCChanging = True
If Double.TryParse(DegreesF.Text, Temperature ) Then
DegreesC.Text = ((Temperature - 32.0) / 9.0 * 5.0).ToString("0.##")
Else
DegreesC.Text = String.Empty
End If
DegreesCChanging = False
End If
End Sub
Private Sub DegreesC_TextChanged(sender As Object, e As EventArgs) Handles DegreesC.TextChanged
If Not DegreesCChanging Then
Dim Temperature As Double
DegreesFChanging = True
If Double.TryParse(DegreesC.Text, Temperature ) Then
DegreesF.Text = (Temperature / 5.0 * 9.0 + 32.0).ToString("0.##")
Else
DegreesF.Text = String.Empty
End If
DegreesFChanging = False
End If
End Sub
There are a few things to note.
I'm using the TextChanged event - as soon as the user types
something into either text box, the world starts changing
I use double.TryParse to convert the number to a string. If I can't figure out what's going on (i.e., the TryParse call returns False), I stick an empty string in the other text box. It works quite well.
When the user types something into a text box, it causes a TextChanged event that forces new text into the other text box - which will result in a TextChanged event for that control. I use two Boolean flags to prevent this.
I use a custom numeric format string on my ToString calls to limit
the precision to two decimal places.

How to make Datagridview Editable and Change it to Number Format?

Good Morning.
I have a Datagridview in a Form and it is connected in Database and it looks like this.
I have no problem with this part.
My question here is like this. How can I make the Fourth Column Editable? I mean I can edit it by clicking this property
and now the output will be like this.
Now here is the real question, I will ask a question based on the flow that my system will do.
1.The 4th Column are the column that will become editable and the rest will be locked or uneditable
2.Lets say I will put 48 how can I make it 48.00 when i leave the cell? That kind of format with .00 at the end.
3.Unable to input Letters on the 4th column.
TYSM for future help
Set the ReadOnly property to True for any column that you don't
want the user to be able to edit.
Set the DefaultCellStyle.Format property of the column to "n2" or "f2".
I'd probably advise against that because the fact that you want to include a decimal point makes it more complex. If you're determined to go ahead then you should research how to allow only numeric input in a regular TextBox, because this will work exactly the same way. You simply need to access the TextBox control used for editing via the appropriate event handlers of the grid.
In the example below, because the editingTextBox field is declared WithEvents, the last method will handle the TextChanged event for the editing control while it's assigned to that field for the duration of the editing session.
Private WithEvents editingTextBox As TextBox
Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
Me.editingTextBox = DirectCast(e.Control, TextBox)
End Sub
Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
Me.editingTextBox = Nothing
End Sub
Private Sub editingTextBox_TextChanged(sender As Object, e As EventArgs) Handles editingTextBox.TextChanged
'...
End Sub
Set the other columns to readonly = true and your numeric column = false and set the defaultcellstyle.format of your numeric column to "###,##0.00" and in your datagridview's cellvalidating event, do the ff:
Private Sub DatagridView1_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DatagridView1.CellValidating
Try
If DatagridView1.IsCurrentCellDirty Then
Select Case DatagridView1.Columns(e.ColumnIndex).Name.ToUpper
Case "<NAME OF YOUR NUMERIC COLUMN>"
If Not IsNumeric(e.FormattedValue) Then
MsgBox("Invalid value.")
e.Cancel = True
Exit Sub
End If
If CType(e.FormattedValue, Integer) < 0 Then
MsgBox("Invalid value.")
e.Cancel = True
Exit Sub
End If
End Select
End If
Catch ex As Exception
ErrMsg(ex)
End Try
End Sub
Private Sub dgvwithdraw_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvwithdraw.CellClick
Select Case dgvwithdraw.Columns(e.ColumnIndex).Name
Case "Select", "Alloted"
dgvwithdraw.ReadOnly = False
Case Else
dgvwithdraw.ReadOnly = True
End Select
End Sub

VB TextBox entry handling - TAB key missing

Windows 10/VS 2015 Community/Visual Basic 2014
I have written the following to input text from 13 TextBoxes. It inputs
each character with its own event. Each character is checked for being
a valid character (numerals, letters, symbols) plus Cr (to move to next
TextBox) and BS (to permit typo corrections). This works:
'===== Enter Frequency =====
Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
ichar = e.KeyChar()
ckinchar() 'ck for input characters, or CR or BS keys
If eoline = 1 Then 'has <cr> been detected?
freq = inline 'Yes
bufcnt = 0 'Reset counter
eoline = 0 'Rest EOL flag
TextBox1.BackColor = Color.LightGreen
TextBox2.BackColor = Color.LightPink
TextBox2.Focus()
Exit Sub
Else
TextBox1.Focus() 'No - repeat inputting
End If
End Sub
Problem: I wish to also use the TAB key (to be implemented as the Cr key)
However the TAB key code fails to appear. In run mode pressing the Tab key
causes the cursor to move up the displayed TextBoxs following the tabIndex order. I've tried using KeyDown/Enter/TextChanged events to no effect -
mostly problems getting implemented.
Can anyone suggest any errors I might have in first two lines, or alternative choice. Is/are there any Properties in the TextBox I should be looking at.
TIA Day Watson
Private Sub TextBox1_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles TextBox1.PreviewKeyDown
If e.KeyCode = Keys.Tab Then
Me.Text = "TAB Captured"
End If
End Sub

Toggle the masking and unmasking of a TextBox using a CheckBox

I have a TextBox, which has a CheckBox operation to mask the containing text. This works with the following code:
Private Sub CheckBox2_Checked(ByVal sender As Object, ByVal e As EventArgs) Handles CheckBox2.CheckedChanged
TextBox14.PasswordChar = "*"
End Sub
It works well, but I want to also be able to uncheck theCheckBox and then have the recognizable text return. How can I achieve this?
The docos actually state:
The character used to mask characters entered in a single-line TextBox
control. Set the value of this property to 0 (character value) if you
do not want the control to mask characters as they are typed. Equals 0
(character value) by default.
Found here: http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.passwordchar(v=vs.110).aspx
In VB.NET, that would be easiest done by setting PasswordChar to vbNullChar.
You can do so by simply setting the PasswordChar property back to a null character, like this:
Private Sub CheckBox2_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles CheckBox2.CheckedChanged
If CheckBox2.Checked Then
TextBox14.PasswordChar = "*"c
Else
TextBox14.PasswordChar = ControlChars.NullChar
End If
End Sub
The CheckedChanged event occurs every time the Checked property changes. So, when the user unchecks the CheckBox, it will raise that event too, so you need to check to see whether or not the control is currently checked.
I found just toggling the password character wasn't enough. In my case I was masking a connection string. With the lack of spaces in my text I had an issue going back and forth. My text would be cut off and wasn't wrapping properly.
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs)
Dim beforeText As String = TextBox1.Text
TextBox1.Text = ""
TextBox1.PasswordChar = IIf(CheckBox1.Checked, Convert.ToChar(0), "*"c)
TextBox1.Text = beforeText
End Sub
I imagine if you used a font like Console this would not be a problem as all character widths are constant.