Make richtextbox single line only - vb.net

Is it possible to make a richtextbox only able to contain one line? I want it to have the wraptext ability but I can't have multiple lines in the file it will generate.

You can set its AcceptsReturn attribute to false that should only allow one line because it won't let the text return.
If for some reason your properties window doesn't have the AcceptsReturn property, you can add if e.KeyCode = Keys.Enter Then e.SuppressKeyPress = True under the event KeyDown (as suggested by Jimi).

Simply think first,how do we get to the next line ? By pressing Return or Enter.So,in the KeyPress event of the RichTextbox you can simply use :
If e.KeyChar = Keys.Return Then
e.Handled = True
End if
Now this has a major drawback and that is : What if a user copy pastes a multi-line text into the richtextbox ?
To fix that, you can simply apply the following code in the TextChanged event :
Private Sub Rtb_TextChanged()
Dim lcount as Integer = rtb.Lines.Count
Dim i As Integer
If lcount > 1 Then
For i = 2 to lcount - 1
Dim index As Integer = rtb.GetFirstCharIndexFromLine(i)
Dim count As Integer = rtb.GetFirstCharIndexFromLine(i + 1) - start_index
rtb.Text = rtb.Text.Remove(index, count)
Next
End if
End Sub
Hope this helps :)

Related

Split string into Sub String

I Am Using Vb.net. My idea is when I paste (ctrl+v) for example this character :
AHAKAPATARAE
I Have 6 textboxes.
it would automatically paste them in textboxes one by one in order!
so
txtBox1 will contain : AH
txtBox2 : AK
txtBox3 : AP
txtBox4 : AT
texbox5 : AR
texbox6 : AE
The automation of inserting Licence Keys will ease so much
so that user will not work so hard to cut & paste each two digits!
so any suggestion of doing auto-fill inside textboxes..?
Thanks.
This will allow the paste into the first textbox, as well as move forward correctly if the user types the whole thing manually starting in the first box:
Private Sub txtBox1_TextChanged(sender As Object, e As EventArgs) Handles txtBox6.TextChanged, txtBox5.TextChanged, txtBox4.TextChanged, txtBox3.TextChanged, txtBox2.TextChanged, txtBox1.TextChanged
Dim TB As TextBox = DirectCast(sender, TextBox)
Dim value As String = TB.Text
If value.Length > 2 Then
TB.Text = value.Substring(0, 2)
Dim TBs() As TextBox = {txtBox1, txtBox2, txtBox3, txtBox4, txtBox5, txtBox6}
Dim index As Integer = Array.IndexOf(TBs, TB)
If index > -1 AndAlso index < (TBs.Length - 1) Then
index = index + 1
TBs(index).Text = value.Substring(2)
TBs(index).Focus()
TBs(index).SelectionStart = TBs(index).TextLength
End If
End If
End Sub
There are definitely many more ways this could be accomplished...
Handle the key down event on textbox 1
Private Sub txtBox1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtBox1.KeyDown
If e.Modifiers = Keys.Control AndAlso e.KeyCode = Keys.V Then
' Get Clipboard Text
Dim cpText as String = My.Computer.Clipboard.GetText()
' Assign
txtBox1.Text = cpText.Substring(0, 2)
txtBox2.Text = cpText.Substring(2, 2)
txtBox3.Text = cpText.Substring(4, 2)
txtBox4.Text = cpText.Substring(6, 2)
txtBox5.Text = cpText.Substring(8, 2)
txtBox6.Text = cpText.Substring(10, 2)
'the event has been handled manually
e.Handled = True
End If
End Sub
Another option is to have one masked textbox event. Might be easier

How to find the highest number in all textboxes

I'm close to finishing a small program that i started, but got stuck with the last part. And I'm just starting to learn programming, so might be a stupid question.
How can i get the text box with the highest number out of 16 boxes,each having its own number, but at the same time keep track of which one still has the highest number every second? Quite confused about the updating it every second part.
All help is appreciated!
Code suggestion
Private Sub findTopTextBox()
Dim topValue As Integer
Dim topTextBox As TextBox
For Each ctrl As Control In Me.Controls 'all the controls on your form
If TypeOf ctrl Is TextBox Then
Dim thisValue As Integer
If Integer.TryParse(DirectCast(ctrl, TextBox).Text, thisValue) Then
If thisValue > topValue Then
topValue = thisValue
topTextBox = DirectCast(ctrl, TextBox)
End If
End If
End If
Next
Debug.Print(String.Concat(topTextBox.Name, " has the top value at: ", topValue))
End Sub
In order to test it each second, you'll need to add a Timer and call this method repeatedly.
You don't really need to check every second only check when a change was made in one of those textboxes
You could handle all your textboxes LostFocus event (using the same method to handle them all) ; get it's text, verify it's a number and if it's greater than the current max update it (along with it's "location" : the textbox control)
That way you always know which one is the greatest
Something along this should do it (typed directly here so not tested) :
Dim maxNumber As Integer, maxTextBox As TextBox
Sub TextBoxes_LostFocus(sender As Object, e As EventArgs) Handles textbox1.LostFocus, textbox2.LostFocus ' ... for all textboxes
Dim tbSender = DirectCast(sender, TextBox)
Dim number As Integer
' Should we update maxTextBox if number = maxNumber ? (if yes change the > to >=)
If Integer.TryParse(tbSender.Text, number) AndAlso number > maxNumber Then
maxNumber = number
maxTexBox = tbSender
End If
End Sub

RichTextBox find and color text visual basic

Hi i have a code for finding words from richtextbox and change font color, the code is working but i f i go back and edit the previous text to something that i don't want to color, the color doesn't go away. here is my code
Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
Dim S As Integer = RichTextBox1.SelectionStart
Dim html() As String = {"<!DOCTYPE html>", "<html>", "</html>", "<head>", "</head>", "<body>", "</body>", "pre>", "</pre>", "<!DOCTYPE>", "<title>", "</title>", "<a>",
"<abbr>", "<address>", "<area>", "<article>", "<aside>", "<audio>", "<acronym>", "<applet>", "<b>", "<base>", "<bdi>", "<bdo>", "<blockquote>", "<body>", "<br>", "<button>", "<basefont>", "<bgsound>", "<big>", "<blink>"}
For i As Integer = 0 To html.Length - 1
Dim str As String = html(i)
Dim start As Integer = S - str.Length - 1
If (start >= 0) Then
If (RichTextBox1.Text.Substring(start, str.Length).ToLower.Equals(str)) Then
RichTextBox1.SelectionStart = start
RichTextBox1.SelectionLength = str.Length
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectionStart = S
RichTextBox1.SelectionLength = 0
End If
End If
Next
RichTextBox1.SelectionColor = RichTextBox1.ForeColor
End Sub
When i run the code provided by Воля Або Смерть the half of text is colored in different colors.
EDITED: if you want to extend the code to allow properties, the modification is very simple. Just check if the regualr expression match contains a space or not. If so, then look in the allowed array for the match without any regards to the properties, values, etc. Code modified, and image added.
I know you asked for solution to your approach, but I am advising another approach for what you want to accomplish.
You could easily overcome this problem if you used Regular Expression.
The idea is simple..
At the RichTextBox_TextChanged event, a regular expression match maker iterates through all text and looks for any HTML tag (one that begins with < and ends with >) regardless of the text in-between.
Then instead of looping through all valid HTML tags in your array, one simple line can easily tell if the array Contains the element or not.
Here is my (Tested & Working) Code..
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub RichTextBox1_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles RichTextBox1.TextChanged
Dim current_cursor_position As Integer = Me.RichTextBox1.SelectionStart
'This is useful to get a hold of where is the current cursor at
'this will be needed once all coloring is done, and we need to return
Dim html() As String = {"<!DOCTYPE html>", "<html>", "</html>", "<head>", "</head>",
"<body>", "</body>", "pre>", "</pre>", "<!DOCTYPE>", "<title>",
"</title>", "<a>", "<abbr>", "<address>", "<area>", "<article>",
"<aside>", "<audio>", "<acronym>", "<applet>", "<b>", "<base>",
"<bdi>", "<bdo>", "<blockquote>", "<body>", "<br>", "<button>",
"<basefont>", "<bgsound>", "<big>", "<blink>", "<img>","</img>",
"<input>","</input>"}
Dim pattern As String = "<(.)*?>"
Dim matches As MatchCollection = Regex.Matches(Me.RichTextBox1.Text, pattern)
For Each match In matches
Me.RichTextBox1.Select(match.index, match.length)
Dim lookFor As String = match.ToString
If match.ToString.Contains(" ") Then 'Checking if tag contains properties
lookFor = match.ToString.Substring(0, match.ToString.IndexOf(" ")) & ">"
'This line will strip away any extra properties, values, and will
' close up the tag to be able to look for it in the allowed array
End If
If html.Contains(lookFor.ToString.ToLower) Then
'The tag is part of the allowed tags, and can be colored green.
Me.RichTextBox1.SelectionColor = Color.Green
Else
'This tag is not recognized, and shall be colored black..
Me.RichTextBox1.SelectionColor = Color.Black
End If
Next
Me.RichTextBox1.SelectionStart = current_cursor_position
'Returning cursor to its original position
Me.RichTextBox1.SelectionLength = 0
'De-Selecting text (if it was selected)
Me.RichTextBox1.SelectionColor = Color.Black
'new text will be colored black, until
'recognized as HTML tag.
End Sub
End Class
PS: you could also avoid expanding your html array of allowed elements, by simply using a regular expression to look for valid HTML tags (with flexibility of spaces between tags, properties and values, etc.
If you wish, I could elaborate on this.
You are actually pretty close. Take the RichTextBox1.SelectionColor = RichTextBox1.ForeColor line out of the loop and you're golden.
For Each elem As String In html
Dim start As Integer = S - elem.Length - 1
If (start >= 0) Then
If (RichTextBox1.Text.Substring(start, elem.Length).ToLower.Equals(elem)) Then
RichTextBox1.SelectionStart = start
RichTextBox1.SelectionLength = elem.Length
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectionStart = S
RichTextBox1.SelectionLength = 0
End If
End If
Next
RichTextBox1.SelectionColor = RichTextBox1.ForeColor

How to color multiple text from richtextbox in vb.net

So I made a chat in vb.net (using FTP server) and I want to color each name from my chat
so the file with messages is something like the following:
#2George: HI
#2George: Hi geoo
and using RichTextBox1 textchanged event I add:
For Each line In RichTextBox1.Lines
If Not line Is Nothing Then
If line.ToString.Trim.Contains("#2") Then
Dim s$ = line.Trim
RichTextBox1.Select(s.IndexOf("#") + 1, s.IndexOf(":", s.IndexOf("#")) - s.IndexOf("#") - 1)
MsgBox(RichTextBox1.SelectedText)
RichTextBox1.SelectionColor = Color.DeepSkyBlue
End If
End If
Next
the first name (George) changed his color but the second one didn't.
Any ideas why this is happening?
The main problem is that your IndexOf calculations are using the index of the current line, but you are not translating that index to where that line is being used in the RichTextBox. That is, your second line of #2George: Hi geoo is finding an index of 0 for the # sign, but index 0 in the RichTextBox is referring to the line #2George: HI, so you keep redrawing the first line every time.
To fix the immediate problem:
For i As Integer = 0 To RichTextBox1.Lines.Count - 1
Dim startIndex As Integer = RichTextBox1.Text.IndexOf("#", _
RichTextBox1.GetFirstCharIndexFromLine(i))
If startIndex > -1 Then
Dim endIndex As Integer = RichTextBox1.Text.IndexOf(":", startIndex)
If endIndex > -1 Then
RichTextBox1.Select(startIndex, endIndex - startIndex)
RichTextBox1.SelectionColor = Color.DeepSkyBlue
End If
End If
Next
The next problem is that doing this in the TextChanged event re-draws all the lines all the time. That won't scale too well. Consider drawing the text before you add it to the control by using a preformatted RTF line. Something like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddRTFLine("#2George", "Hi")
AddRTFLine("#2George", "Hi geoo")
End Sub
Private Sub AddRTFLine(userName As String, userMessage As String)
Using box As New RichTextBox
box.SelectionColor = Color.DeepSkyBlue
box.AppendText(userName)
box.SelectionColor = Color.Black
box.AppendText(": " & userMessage)
box.AppendText(Environment.NewLine)
box.SelectAll()
RichTextBox1.Select(RichTextBox1.TextLength, 0)
RichTextBox1.SelectedRtf = box.SelectedRtf
End Using
End Sub

What's the best way to create a drop-down list in a Windows application using Visual Basic?

I'd like to add a drop-down list to a Windows application. It will have two choices, neither of which are editable. What's the best control to use? Is it a combo box with the editing property set to No?
I'm using Visual Studio 2008.
I'd suggest taking a look at the Windows Vista User Experience Guide. It sounds like you might be better off with radio buttons, or, if it's an explicit on/off type of situation, using a check box. I think we'd really need more info, though.
yourComboBox.DropDownStyle = ComboBoxStyle.DropDownList
Set the DropDownStyle property to DropDownList.
See http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.dropdownstyle(VS.80).aspx
The combobox in winforms doubles as a uneditable drop down list by changing the DropDownStyle property to "DropDownList": I don't think there is a separate drop down list control.
Create two text boxes next to each other TextBox1 and TextBox2, for TextBox2 set multiple lines and autosize.
create your dropdown list somewhere. In my example it was in a different sheet with about 13,000 entries.
Below are two functions, the first drives the input box, TextBox1. as you type, the 2nd box, TextBox2 shows the remaining valid choices. The second function, loads the first textbox if you click on a choice in the second box
In the below, cell B3 on the current sheet had to be loaded with the typed/selected answer. In my application, I only wanted to search for uppercase characters hence the UCase usage. My list data was 13302 entries in column Z
Private Sub TextBox1_Keyup(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim curtext As String
Dim k, where As Integer
Dim tmp As String
Dim bigtmp As String
curtext = TextBox1.Text
curtext = UCase(curtext)
TextBox1.Text = curtext
Range("b3").Value = curtext
If Len(curtext) = 0 Then
TextBox2.Visible = False
Exit Sub
End If
TextBox2.Visible = True
Application.ScreenUpdating = False
For k = 2 To 13303 ' YOUR LIST ROWS
tmp = Sheets("General Lookup").Range("Z" & k).Value ' YOUR LIST RANGE
where = InStr(1, tmp, TextBox1.Text, 1)
If where = 1 Then
bigtmp = bigtmp & tmp & Chr(13)
End If
Next
TextBox2.Text = bigtmp
Application.ScreenUpdating = True
End Sub
Private Sub TextBox2_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
If Len(TextBox2.SelText) > 0 Then
TextBox1.Text = TextBox2.SelText
Range("b3").Value = TextBox2.SelText
TextBox2.Visible = False
End If
End Sub