validate a textbox in vb.net - 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.

Related

Filling a listbox from a textbox without using a button or click event in VB

I'm not sure if it is possible, but I would like to know if a listbox can be updated by adding or removing text by typing that text into a textbox without using a button event or some type of click event. I've tried using the text_changed event but it inserts the text as I type so I am unable to type an entire string and then move that into a listbox as a whole string.
What I am trying to do is scan a magnetic ID card through a reader and have it insert the data from that card into a listbox and when I scan the same card again, it will remove the data. This is for an employee logging system.
Thanks.
With the following code, if you type a string in TextBox1 and hit Enter, we check to see if the string already exists in ListBox1. If so, the string is removed from the ListBox, otherwise it is added. Then TextBox1 is cleared.
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar = vbCr Then
If ListBox1.Items.Contains(TextBox1.Text) Then
ListBox1.Items.Remove(TextBox1.Text)
Else
ListBox1.Items.Add(TextBox1.Text)
End If
TextBox1.Clear()
e.Handled = True
End If
End Sub

For each new line do something

i have a textbox called txtChat and i want that for every new line the textbox2 and textbox3 gets refreshed.. i dont know how to make thits "new line thing" or which commmand is the right one. Im looking for something like
For Each NewLine refresh textbox2&3
If you wish to monitor the input into a textbox as the user types you could use the keypress event. The parameter e.KeyChar then corresponds to the keyboard key pressed by the user. If it is equal to vbCr you can conclude the user pressed enter. Your code should probably look something like this:
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar = vbCr Then
'Refresh textboxes 2 and 3
End If
End Sub
You would get into trouble though if, for example, the user copy-pasted something in, as the user will then not have entered a newline character.
As Dries says, you could use the textchange event, in which case you would have to check what the last character entered into the textbox is. Slightly confusingly, in this case, you would have to check if the text ends with a vbCrLf.
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If TextBox1.Text.EndsWith(vbCrLf) Then
'Refresh textboxes 2 and 3
End If
End Sub
Take a look at the TextChange Event.
(https://msdn.microsoft.com/en-us/library/system.windows.forms.control.textchanged(v=vs.110).aspx)
It should point out what you're looking for (as far as I understand).

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

Eliminate user input of single quote for every field in every form in a project

using VB.net and Visual studio is there a way to globally (across all fields in all forms in a project) prevent a user from entering a single quote character into a field. I'm thinking some sort of modification of the keypress event, but I'm not sure how to go about it. Currently I am currently using the ADDHANDLER, ADDRESSOF technique to assign this special code to a particular field, and I guess I could do a loop over all my contained controls on a particular form and assign the keypress code, but if there is a way to do it once without repeating the code on each form that would be great. Any hints graciously accepted. Thanks.
What about a regex? Stripping or converting to escape character on submit?
Would it be possible to pass an array where TextBox1 is TextBox1,Textbox2, etc. Obviously you would need to edit the expression if you only need to strip the single quote. This for all non alphabet characters. I don't do much with vb.net but thought this might be helpful.
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
StripNonAlphabetCharacters(TextBox1)
End Sub
Public Sub StripNonAlphabetCharacters(ByVal input As TextBox)
' pattern matches any character that is NOT A-Z (allows upper and lower case alphabets)
Dim rx As New Regex("[^a-zA-Z]")
If (rx.IsMatch(input.Text)) Then
Dim startPosition As Integer = input.SelectionStart - 1
input.Text = rx.Replace(input.Text, "")
input.SelectionStart = startPosition
End If
End Sub
The easiest solution is to create a derived TextBox and use that instead of the standard textbox.
Public Class NoQuoteTextBox
Inherits TextBox
Public Sub New()
AddHandler MyBase.KeyPress, AddressOf Handler
End Sub
Public Sub Handler(ByVal sender As Object, ByVal e As KeyPressEventArgs)
If e.KeyChar = "'" Then
e.Handled = True
End If
End Sub
End Class
Build your project then the NoQuoteTextBox (or whatever you decide to call it) will appear in the Toolbox in the Designer:
Use this new control instead of the standard textbox and it will handle the single quote for you.

how to format text box during input in 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 ###.###