how to format text box during input in vb.net - vb.net

I have 200+ text boxes in vb.net application. Let me make it clear all are simple text boxes. now customer demand to have formatted number value while input or viewing record. With Format() i can play for viewing but during add/edit mode in text box (While user typing value) nothing happened
I want this result 1234567.0090 to 1,234,567.0090 during input.
or guide me any way by which i change all text boxes to mask textboxes through any tool or code.
Any help appreciated. Thanks in Advance.

First, I would recommend very strongly that you try to talk your customer out of this requirement. Masked text boxes in general are a royal pain in the butt, both for the programmer and for the end user. In my opinion, if you must format user input, it is far better to format whatever they have entered after the control loses focus than to attempt to format their input while they are still typing it.
With either approach, the easiest way to do this is to create your own user control (unless you want to use a third-party control, which I wouldn't advise for this purpose for a bunch of reasons) that inherits from TextBox (instead of inheriting from UserControl). If you wish to format the text after the user has finished entering input and has moved on to another control, you can add an EventHandler to your control's LostFocus event and format their input there.
If, however, you wish to format as they're typing, you have a couple of grisly choices. First, you can handle the control's KeyPress or KeyDown events, and intercept-and-cancel non-numeric characters, or else format the overall Text property at this time. This is a common approach which often fails in unexpected ways, since it ends up not dealing with text that is copy-and-pasted into the control (which happens quite often in data-entry applications).
An alternative approach is to handle the TextChanged event, which will respond to both keyboard input and pasted-in text, and re-format the text on the fly. Since you're often changing the text as they type, your code needs to pay attention to the SelectionStart property (among others), so that you don't unexpectedly change the caret's position as the user is typing. Also, when you change your control's text property while formatting it, this change will itself produce another TextChanged event, so you need to be careful that you don't get stuck in an endless loop.
To reiterate my main point, you will be much happier formatting in the LostFocus event, and so will your end users.
Once you've written your control, you can just do a global replace in your code, substituting "MyMaskedTextBox" for "TextBox" (case-sensitivity is recommended here).
Update: Here is some simple parsing/formatting code you can use in your TextBox's LostFocus event:
double d;
TextBox tb = (TextBox)sender;
if (double.TryParse(tb.Text, out d))
{
tb.Text = d.ToString("#,###,###,###.0000");
tb.BackColor = SystemColors.Window;
}
else
{
tb.BackColor = Color.Red;
}
This code will format the user's input as a number in the way that you require if the text entered can be parsed as a double. If the input is not a valid double, the text is left as is and the BackColor is changed to red. This is a good way of indicating invalid input to the user (as opposed to popping up a MessageBox).

Override these events in your text box derived custom control. But, remember no formating as they're typing,
Protected Overrides Sub OnLostFocus(ByVal e As System.EventArgs)
MyBase.OnLostFocus(e)
Me.Text = Strings.FormatNumber(Me.Text, _
m_FormatNumDigitsAfterDecimal, _
m_FormatIncludeLeadingDigit, _
m_FormatUseParensForNegativeNumbers, _
m_FormatGroupDigits)
End Sub
Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)
MyBase.OnTextChanged(e)
If Me.Focused = False Then
Me.Text = Strings.FormatNumber(Me.Text, _
m_FormatNumDigitsAfterDecimal, _
m_FormatIncludeLeadingDigit, _
m_FormatUseParensForNegativeNumbers, _
m_FormatGroupDigits)
End If
End Sub

That´s another method.
Private Sub TBItemValor_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TBItemValor.KeyPress
If (Char.IsDigit(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False AndAlso Char.IsPunctuation(e.KeyChar) = False) OrElse Not IsNumeric(Me.TBItemValor.Text & e.KeyChar) Then
e.Handled = True
End If
End Sub

Public Sub checktextbox2(txt As TextBox)
dim bg as string
For t = 1 To txt.Text.Length
If txt.Text.Chars(txt.Text.Length - (txt.Text.Length - t)) = "." Then
bq = txt.Text.TrimEnd(New String({"0", "."}))
txt.Text = bq
Exit For
End If
Next
end sub
this will format number in textbox as ###.###

Related

VB.NET How can I change cursor direction to right-to-left or left-to-right?

I have a vb.net form that containing 2 richtextbox. The first richtextbox in English and the second in Arabic. How can I change the cursor direction so that its direction turns to the right when entering the Arab richtextbox and to the left when entering the English richtextbox??
All controls have a property named RightToLeft which is used to dictate the direction of text entry.
Here it is as described in the docs:
Gets or sets a value indicating whether control's elements are aligned
to support locales using right-to-left fonts.
In the case of your RichTextBoxes, either set the property in the Properties window in the Form editor, or programatically like this:
EnglishRichTextBox.RightToLeft = RightToLeft.No
ArabicRichTextBox.RightToLeft = RightToLeft.Yes
If the RichTextBoxes are dedicated for English or Arabic input, you should set them at design time. There is a side effect of changing the value at runtime (in code), which is detailed in the docs:
If the value of the RightToLeft property is changed at run time, only
raw text without formatting is preserved.
Perhaps you mean changing the input language on enter a RichTextBox control? If that's what you are after, then you need to handle the Enter event of each RTB to switch the language through the InputLanguage class. The class has static properties to get the installed input languages, their cultures, the default and the current input languages.
Add Enter event handler for each RTB and handle them as follows:
The English Language RTB
Private Sub enRTB_Enter(sender As Object, e As EventArgs) Handles enRTB.Enter
Dim lang = InputLanguage.InstalledInputLanguages.
Cast(Of InputLanguage).
FirstOrDefault(Function(x) x.Culture.TwoLetterISOLanguageName = "en")
If lang IsNot Nothing Then InputLanguage.CurrentInputLanguage = lang
End Sub
The Arabic Language RTB
Private Sub arRTB_Enter(sender As Object, e As EventArgs) Handles arRTB.Enter
Dim lang = InputLanguage.InstalledInputLanguages.
Cast(Of InputLanguage).
FirstOrDefault(Function(x) x.Culture.TwoLetterISOLanguageName = "ar")
If lang IsNot Nothing Then InputLanguage.CurrentInputLanguage = lang
End Sub

Forcing a combo box to update its text field

I have a typical combobox with drop down items. An item in the dropdown consists of a string with a code then a space, then the description of the code. I'm trying to get the text of the combo box to show just the code after the selection has been made, but there is a race condition in which my the text field is not being updated by the combobox until AFTER I change it. How do I force the combobox to update itself, so I can change the text afterwards.
With code_combo_box
AddHandler .SelectedIndexChanged, AddressOf update_desc
End With
Private Sub update_desc()
If code_combo_box.SelectedIndex >= 0 Then
Dim temp_string As String() = code_combo_box.SelectedItem.split(" ")
code_combo_box.Text = temp_string(0)
End If
End Sub
The combobox gets updated to the selected item after update_desc is called wiping out my change.
I figured out the answer which is to flag the event as handled when I enter the update_desc subroutine. So I needed to catch the events when entering the routine with
update_desc(sender as object, e as system.eventargs)
and then inside the routine simply use
e.handled = true
and the event would not continue to fire after leaving the routine and my changes would remain.

How to Dynamically Update Label with TextBox As Input Changes

I have a spelling application that I am building in VB.Net, where I have a textbox receiving simple input (spelling words), and a label which will show the output. What I want to accomplish is when I enter something in the textbox, I can see it in my label - as I am typing into the textbox.
I will admit that I don't know what I'm doing, as I've never tried this before, so I don't know to begin in terms of setting up what I need to do. I know that I'll need some variable to hold my String input, and will probably need some type of loop, but beyond that, I am lost. The only other example is in C#, and doesn't help me any.
Can anyone give me a simple model to work off of, so I can put the approach into memory? For now, all I have is code stub from my TextChanged event handler:
Private Sub txtSpell_TextChanged(sender As Object, e As EventArgs) Handles txtSpell.TextChanged
'Set variables to hold values.
Dim someText As String
'Connect the label and textbox.
lblShowInput.Text = txtWordInput.Text
'Process loop to populate the label from textbox input.
for '(This is where I am lost on the approach)
End Sub
I know that I'll need some variable to hold my String input, and will
probably need some type of loop
I don't think you'll need a loop, or the variable to hold the value. You almost have it:
Private Sub txtSpell_TextChanged(sender As Object, e As EventArgs) Handles txtSpell.TextChanged
'Connect the label and textbox.
lblShowInput.Text = txtSpell.Text
End Sub
In the code you provided, you are referencing an object named txtWordInput inside your txtSpell text changed event handler. If you are entering the text in the txtWordInput input, you'll want to handle this in the txtWordInput textChanged event handler:
Private Sub txtWordInput_TextChanged(sender As Object, e As EventArgs) Handles txtWordInput.TextChanged
'Connect the label and textbox.
lblShowInput.Text = txtWordInput.Text
End Sub
Follow-up:
The TextChanged event is the correct event for this.
In your code, you are assigning lblShowInput.Text to txtWordInput.Text, but in the txtSpell TextChanged event handler.
You want to be in the TextChanged event handler for whatever TextBox you would like to use to update the label, as the text is changing.
To give a better example, I have created a simple Winforms VB application that has only a textbox named InputTextBox and a label named Output Label.
The Form:
The Code:
Public Class Form1
Private Sub InputTextBox_TextChanged(sender As System.Object, e As System.EventArgs) Handles InputTextBox.TextChanged
OutputLabel.Text = InputTextBox.Text
End Sub
End Class
Explanation:
InputTextBox_TextChanged is the method name generated by Visual Studio for our event handler
Handles InputTextBox.TextChanged ties the method to an actual event it is handling.
When the InputTextBox text property is changed (typically by user input), whatever we have in our InputTextBox_TextChanged Sub will execute. In this case, I am assigning the Text of OutputLabel to the Text of the InputTextBox
Output:
Resources:
I've uploaded this simple demo to GitHub if you'd like a closer look.
Take a look at the TextChanged documentation

validate a textbox in vb.net

How could i validate a textbox in vb.net, so that it gives error message if i enter anything apart from alphabets
You can check the text string, i.e., textbox1.text, to make sure it has nothing besides alphabet characters in the .Leave event. This will catch an error when the user tabs to the next control, for example. You can do this using a regular expression (import System.Text.RegularExpressions for this example), or you can check the text "manually."
Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave
If Not Regex.Match(TextBox1.Text, "^[a-z]*$", RegexOptions.IgnoreCase).Success Then
MsgBox("Please enter alpha text only.")
TextBox1.Focus()
End If
End Sub
If you want to stop the user as soon as a non-alpha key is pressed, you can use the TextChanged event instead of the .Leave event.
CustomFieldValidator with a regex.
If it's a standard textbox in a WinForms app you can validate every typed character by handling the KeyPressed event and have the following code in the event handler:
e.Handled = Not Char.IsLetter(e.KeyChar)
The user could still use the mouse to paste something in there though so you might need to handle that as well.
Another option is to handle the Validating event and if the textbox contains any non alphabetic characters you set e.Cancel to true.

Visual Studio AutoComplete simulates enter being pressed when selecting

Visual studio nicely provides built-in auto-complete functionality for text boxes and combo boxes. I am using the suggest method of auto complete that provides the user with a list of choices filteres by what they have type. The problem I am having is that when the user makes a selection (via the mouse) VS places the selected text into the textbox and also simulates the enter key being pressed on the textbox.
In my program the enter keyup event is used to send the text entered in the text box to the a COM port. In order for this to work as desired the user must be able to select an auto-complete option and then add to it so that they can change settings.
Is it possible to stop it from triggering that event or to intercept it? I am unsure if it is possible or how to determine the origin of a keypress.
Here is the code for the KeyUp even as well as for the KeyPress Event:
Private Sub txtInput_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtInput.KeyPress
If e.KeyChar = Chr(13) Then
e.Handled = True
End If
End Sub
Private Sub txtInput_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtInput.KeyUp
If e.KeyValue = Keys.Enter Then
If txtInput.Text.ToLower = "cls" Or txtInput.Text.ToLower = "clr" Or txtInput.Text.ToLower = "clear" Then
txtOutput.Text = ""
Else
If SerialPort1.IsOpen Then
SerialPort1.Write(txtInput.Text)
Else
MsgBox("The serial port is not open")
End If
End If
txtInput.Text = ""
e.Handled = True
e.SuppressKeyPress = True
End If
End Sub
The auto-complete functionality was accomplished through the properties of the control, the only code for that was to generate the auto-complete list.
Thanks in advance for any help.
P.S. I am using VB.net, but if necessary I can figure out how to get it from another .net language to VB
After researching it, I haven't been able to find a standard way to do what you want to do without overriding the functionality of the built-in AutoComplete.
You will have to create your own AutoComplete class for Textboxes and just don't implement the MouseEventHandler like you normally would in the example code below for a traditional AutoComplete list:
private void List_MouseDown(object sender, MouseEventArgs e)
{
for (int i=0; i<this.list.Items.Count; i++)
{
if (this.list.GetItemRectangle(i).Contains(e.X, e.Y))
{
this.list.SelectedIndex = i;
this.SelectCurrentItem();
}
}
this.HideList();
}
CodeProject has a good example of a custom AutoComplete TextBox in C#. Good luck.