keep track of richtext box text? - vb.net

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.

Related

How to filter unbound datagridview with textbox vb.net?

I'm a complete rookie. I learned so much from here but this one I can't find the answer to. I'm using Visual Studio Pro 2015.
I have a windows form application that has a single column datagridview that is populated by reading a textfile, line by line at runtime. Each time the contents of the textfile will be different.
I want the user to be able to filter the list in the datagridview by entering characters in a textbox. The data is not "bound" to the datagridview, because at this point I don't know if that is necessary, and I don't completely understand it.
This is the code that I have for loading the datagridview, and the textbox is called txtFilter.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'read all lines from the file into a string array (one line per string)
Dim lines() As String = My.Computer.FileSystem.ReadAllText("c:\list_in.txt").Replace(vbLf, "").Split(vbCr)
Dim dgrow As DataGridViewRow
Dim dgcell As DataGridViewCell
'insert each line of input into a row in the datagrid
For Each line As String In lines
dgrow = New DataGridViewRow
dgcell = New DataGridViewTextBoxCell
If line <> "" Then
dgcell.Value = line
dgrow.Cells.Add(dgcell)
DataGridView1.Rows.Add(dgrow)
End If
Next
DataGridView1.Columns("ObjectName").ReadOnly = True
DataGridView1.ClearSelection()
End Sub
Edit:
Looking at your solution, I would advise you execute Dim lines() As String = My.Computer.FileSystem.ReadAllText("c:\list_in.txt").Replace(vbLf, "").Split(vbCr) outside of the txtFilter_TextChanged sub, as otherwise you are importing the entire list every time the user enters a key, which is unnecessary. If the list may change while the user is using the program, I'd instead recommend adding a 'refresh' button, especially if your text file could be a long one.
You also added a couple lines of code to remove the sound when the user presses the Enter key. If the user is expected to press the enter key to search, then you don't need to update the DataGridView every time the user enters a new character in the textbox. This would be easier on memory, and again very beneficial if you have a large text file.
I'm sure there's an easier way, but here's my approach.
Private Sub txtFilter_TextChanged(sender As Object, e As EventArgs) Handles txtFilter.TextChanged
Dim searchedlines(-1) As String 'create an array to fill with terms that match our search
If txtFilter.Text = Nothing Then
datapopulate(lines) 'just populate the datagridview with our text file array
Else
For Each line In lines
If line Like "*" & txtFilter.Text & "*" Then 'check if anything in our search matches any of our terms
ReDim Preserve searchedlines(UBound(searchedlines) + 1) 'resize the array to fit our needs
searchedlines(UBound(searchedlines)) = line 'add the matched line to our array
End If
Next
datapopulate(searchedlines) 'populate the datagrid with our matched terms array
End If
End Sub
Private Sub datapopulate(ByVal mylist)
Dim dgrow As DataGridViewRow
Dim dgcell As DataGridViewCell
DataGridView1.Rows.Clear() 'clear the grid
For Each line As String In mylist 'do the same thing here that we did on form load
dgrow = New DataGridViewRow
dgcell = New DataGridViewTextBoxCell
dgcell.Value = line
dgrow.Cells.Add(dgcell)
DataGridView1.Rows.Add(dgrow)
Next
End Sub
What I did is created a sub that handles whenever the text in txtFilter is changed. Alternatively, you could run that code in a sub that handles a button click. Given that, from what I know, ReDim can be a costly item in terms of memory usage, if your text document was hundreds of lines long, you might want it on a button click instead. You could probably use a list, but I haven't played around enough to know how to go about doing that.
An important note: in order for the sub txtFilter_TextChanged to be able to see lines(), I defined it outside of a sub but inside of your main class, so that all subs could access it, like so:
Public Class Form1
Dim lines() As String = My.Computer.FileSystem.ReadAllText("c:\list_in.txt").Replace(vbLf, "").Split(vbCr)
'...subs here...
End Class
I hope this helps you get started!
I have a solution working. Thank you very much.
Private Sub txtFilter_TextChanged(sender As Object, e As EventArgs) Handles txtFilter.TextChanged
'read all lines from the file into a string array (one line per string)
Dim lines() As String = My.Computer.FileSystem.ReadAllText("c:\list_in.txt").Replace(vbLf, "").Split(vbCr)
Dim dgrow As DataGridViewRow
Dim dgcell As DataGridViewCell
DataGridView1.Rows.Clear()
'insert each line of input into a row in the datagrid
For Each line As String In lines
dgrow = New DataGridViewRow
dgcell = New DataGridViewTextBoxCell
If line.Contains(txtFilter.Text) Then
dgcell.Value = line
dgrow.Cells.Add(dgcell)
DataGridView1.Rows.Add(dgrow)
End If
Next
DataGridView1.Columns("ObjectName").ReadOnly = True
DataGridView1.ClearSelection()
End Sub
And I also found this to eliminate the bell from ringing when the user pressed the enter key when entering the filter text.
Private Sub txtFilter_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtFilter.KeyPress
' this keeps the bell from ringing when the user presses the 'enter' key
If Asc(e.KeyChar) = 13 Then
e.Handled = True
End If
End Sub

VB.Net get text after keypress

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

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.