VB.Net get text after keypress - vb.net

I am running some custom validations on textbox keypress event.
When a user presses a key I want to find out the text that would exist after that particular key press.
Eg. If the textbox currently contains 12.4 and the user press "6" key I want to find out what the text would be afterwards. I tried appending the e.KeyChar to the end of the textbox.text but there would be problems if the user highlights portions of the textbox and then press a key.
Is there anyway to detect the actual value that would exist after a key has been pressed?

You would have to disassemble the current text based on the current caret position, examine the incoming text, and then reassemble the text again:
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) _
Handles TextBox1.KeyPress
Dim part1 As String = TextBox1.Text.Substring(0, TextBox1.SelectionStart)
Dim part2 As String = TextBox1.Text.Substring(TextBox1.SelectionStart + _
TextBox1.SelectionLength)
Dim character As String = String.Empty
If Char.IsDigit(e.KeyChar) Then
character = e.KeyChar.ToString
Dim result As String = part1 & character & part2
'Do something with result...
Else
e.Handled = True
End If
End Sub

Related

Automatically remove not authorized character on Regular Expressions just after being typed

I'm using this code
Private Sub MyTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles MyTextBox.KeyPress
If Not Regex.Match(MyTextBox.Text, "^[a-z /s ']*$", RegexOptions.IgnoreCase).Success Then
MyTextBox.Text = MyTextBox.Text.Remove(MyTextBox.SelectionStart - 1, 1)
MyTextBox.Select(MyTextBox.Text.Count, 0)
End If
End Sub
so the user can only add letters, space and apostrophe
The code works if the user digit
somethin8g
the number 8 is removed
But if the user just digit
somethin8
the number 8 is visible until the user press another key, and even worst, if the user press the "SAVE" button the info is accepted even with the number 8
Is there a better way to automatically remove not authorized character on Regular Expressions just after being typed?
Generic solution adaptable to any situation (Just changing the allowedChars string)
No regular expression needed
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) _
Handles txtName.KeyPress
If Not (Asc(e.KeyChar) = 8) Then
Dim allowedChars As String = "abcdefghijklmnñopqrstuvwxyzáéíóúàèìòùäëïöüâêîôû '"
If Not allowedChars.Contains(e.KeyChar.ToString.ToLower) Then
e.KeyChar = ChrW(0)
e.Handled = True
End If
End If
End Sub
Adapted from the answer of Jhon Woo on Get a textbox to accept only characters in vb.net

Autocomplete for single word in datagridview

I would need to implement a autocomplete feature in a datagridview cell. I would need it to work on a word by word basis, like it is in the SMS app on android. After I type a whitespace it should start looking for the word I am typing and propose it based on the other words i have already used inside the same Datagridview.
Its more a word suggestion, that if i hit tab autocompletes that word for me.
Is this possible? I know how to do it based on the entire cell, but have no clue on how to do it based on the single word. (like Google)
Thanks
EDIT:
So far I have this. The concept is working, but I need to update the list each time that a key is pressed. Any help on this?
Private Sub DataGridView2_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView2.EditingControlShowing
wrdlst.Add("arabia")
wrdlst.Add("burundi")
wrdlst.Add("closed")
wrdlst.Add("afganistan")
wrdlst.Add("door")
wrdlst.Add("banana")
wrdlst.Add("apple")
Dim basestring As String = Nothing
basestring = CStr(DataGridView2.CurrentCell.Value)
If Not IsNothing(basestring) Then
Dim lastword As String
Dim lastspaceindex As Integer = basestring.LastIndexOf(" ") + 1 '''+1 to get index after whitespace and compensate for -1 result
lastword = basestring.Substring(lastspaceindex)
Dim ItemCode As TextBox = TryCast(e.Control, TextBox)
If ItemCode IsNot Nothing Then
ItemCode.AutoCompleteMode = AutoCompleteMode.SuggestAppend
'ItemCode.AutoCompleteCustomSource = wrdlst
For Each element As String In wrdlst
If element.StartsWith(lastword) Then
ItemCode.AutoCompleteCustomSource.Add(basestring.Substring(0, lastspaceindex) & element)
End If
Next
ItemCode.AutoCompleteSource = AutoCompleteSource.CustomSource
End If
End If
End Sub
Private Sub DataGridView2_KeyUp(sender As Object, e As KeyEventArgs) Handles DataGridView2.KeyUp
??????????????????????????????????????????
End Sub

Capture CTRL+V or paste in a textbox in .NET

VB.NET 2010 - I have a RichTextbox in which the user can manually enter data or copy/paste from another source. After the data is complete he hits go and a few key words are highlighted. My issue is that if he copy/pastes from another source the formatting also gets copied. Well sometimes the outside source has a white font and my textbox has a white background so it appears like he pasted nothing and he does it again and again.
What I'm looking for is a way to intercept the paste action into the textbox so that I can take that text and paste it as pure ASCII without formatting.
Edit after experimenting with KeyDown
Private Sub txtRch_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtRch.KeyDown
If e.Modifiers = Keys.Control AndAlso e.KeyCode = Keys.V Then
With txtRch
Dim i As Integer = .SelectionStart 'cache the current position
.Select(0, i) 'select text from start to current position
Dim s As String = .SelectedText 'copy that text to a variable
.Select(i, .TextLength) 'now select text from current position to end
Dim t As String = .SelectedText 'copy that text to a variable
Dim u As String = s & Clipboard.GetText(TextDataFormat.UnicodeText) & t 'now concatenate the first chunk, the new text, and the last chunk
.Clear() 'clear the textbox
.Text = u 'paste the new text back into textbox
.SelectionStart = i 'put cursor back to cached position
End With
'the event has been handled manually
e.Handled = True
End If
End Sub
This seems to work and all my text gets retained and its all ASCII. I think if I wanted to take a step further I could also take the font and forecolor of my RichTextbox, select all text, and then assign the font and forecolor to the selection.
In most cases, examining the KeyDown event should be good enough along with using a temporary RichTextBox to modify the incoming text:
Private Sub RichTextBox1_KeyDown(sender As Object, e As KeyEventArgs) _
Handles RichTextBox1.KeyDown
If e.Modifiers = Keys.Control AndAlso e.KeyCode = Keys.V Then
Using box As New RichTextBox
box.SelectAll()
box.SelectedRtf = Clipboard.GetText(TextDataFormat.Rtf)
box.SelectAll()
box.SelectionBackColor = Color.White
box.SelectionColor = Color.Black
RichTextBox1.SelectedRtf = box.SelectedRtf
End Using
e.Handled = True
End If
End Sub
Note: Missing any error checking.

limit the range of characters the user can put into a textbox vb.net

I have a textbox in a vb form and I want to limit the range of characters that the user can put into the textbox to:" abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890^-*().". The textbox is to insert SI Units into a database so i need consistent syntax. If the user types an invalid character into the textbox I would like the textbox to refuse to insert it, or remove it straight away, leaving the cursor in the same position within the textbox. I would also like the textbox to replace "/" with "^(-" and place the cursor before this.
I have found some code elsewhere which I have edited to do this but the code is bad, it activates on text changed within the textbox. This causes the code to fail, when the user inputs a disallowed value the code it activates itself when it tries to changes the text within the textbox.
Here is my code, the textbox starts with the contents "enter SI Units" from the form designer.
Private Sub TxtQuantityTextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSIUnit.TextChanged
If txtSIUnit.Text = "Enter SI Units" Then
Exit Sub
End If
Dim charactersAllowed As String = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890^-*()."
Dim Text As String = txtSIUnit.Text
Dim Letter As String
Dim SelectionIndex As Integer = txtSIUnit.SelectionStart
Dim Change As Integer
Letter = txtSIUnit.Text.Substring(SelectionIndex - 1, 1)
If Letter = "/" Then
Text = Text.Replace(Letter, "^(-")
SelectionIndex = SelectionIndex - 1
End If
Letter = txtSIUnit.Text.Substring(SelectionIndex - 1, 1)
If charactersAllowed.Contains(Letter) = False Then
Text = Text.Replace(Letter, String.Empty)
Change = 1
End If
txtSIUnit.Text = Text
txtSIUnit.Select(SelectionIndex - Change, 0)
If txtQuantity.Text <> "Enter Quantity" Then
If cmbStateRateSumRatio.SelectedIndex <> -1 Then
bttAddQUAtoDatabase.Enabled = True
End If
End If
End Sub`
Thanks for you help.
Use the KeyPress event. Set e.Handled to true if you don't like the character. It's a one-liner:
Private Const AllowedChars = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890^-*()."
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As PressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar >= " "c AndAlso Not AllowedChars.Contains(e.KeyChar) Then e.Handled = True
End Sub
In the textbox's KeyDown event, check e.KeyCode. This lets you prevent certain characters from being handled. There's an example on the KeyDown documentation.

keep track of richtext box text?

I'm new to the VB applications.My basic background is C.I just installed VB and learning stuff from google and microsoft help center. and I'm having fun with the things I'm doing but I got stucked up at one point and thats at richtext box.Is there any way to keep track of Rich textbox text in VB? So that I can append some text when user hits new line (i.e enter ) and do some task when he hits backspace. How do i keep track of richtextbox.?
I found
stringer = RichTextBox1.Lines(0) to read lines
& vbNewLine for new line
How do i read that user hit the new line character or backspace in vb rich textbox? because as far in C i used to do like these
if a = 13; \\ ascii for new line and 8 for backspace
I just want to do some task when user hits new line but I am unable to figure it out what the condition to be made.and Any good links for vb and documents on VB or on its windows application would be appreciated Too. Thank you in advance
You will want to link into the KeyDown event for the RichTextBox. Within this event you can modify the Text of the current line. Sample code for adding text to a line is:
Private Sub RichTextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles RichTextBox1.KeyDown
Dim textToAdd As String = " ** text to add **"
'Fire when the Enter key is pressed
If e.KeyCode = Keys.Enter Then
'Get the current cursor position
Dim cursorPos As Integer = RichTextBox1.SelectionStart
'Get the current line index
Dim index As Integer = RichTextBox1.GetLineFromCharIndex(cursorPos)
'Load all the lines into a string array
'This has to be done since editing via RichTextBox1.Lines(index) = "" doesn't always work
Dim lines() As String = RichTextBox1.Lines
'Add the text to the correct line
lines(index) &= textToAdd
'Assign the text back to the RichTextBox
RichTextBox1.Lines = lines
'Move the cursor to the correct position
RichTextBox1.SelectionStart = cursorPos + textToAdd.Length
End If
End Sub
All you need to do is check if the Enter or BackSpace key was pressed, like this:
Private Sub RichTextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles RichTextBox1.KeyDown
Select Case e.KeyCode
Case Keys.Enter
'Do stuff when Enter was pressed
Case Keys.Back
'Do stuff when BackSpace was pressed
End Select
End Sub
Note that Select Case is the same as the switch in C.