Highlight text in a richtextbox in windows forms - vb.net

How to make when i type in a RichTextBox a certain word it gets highlited?
how do i find words in the text to use SelectionColor or SelectionFont
For example: i want that all times that the word "hello" appear in the RichTextBox it turn to bold or turn into a color...
Then if i open my program and type "hello, how are you?" the word hello turns into bold... any idea? (my idea is to make a text editor with syntax highlight that ill specify the words)
(sorry if there is another question like that, i tried to search but i didn't find a answer that helped me)
its windows forms, visual basic

This code should do the work:
Dim searchstring As String = "hello"
' The word you're looking for
Dim count As New List(Of Integer)()
For i As Integer = 0 To richTextBox1.Text.Length - 1
If richTextBox1.Text.IndexOf(searchstring, i) <> -1 Then
'If the word is found
'Add the index to the list
count.Add(richTextBox1.Text.IndexOf(searchstring, i))
End If
Next
Try
For i As Integer = 0 To count.Count - 1
richTextBox1.[Select](count(i), searchstring.Length)
richTextBox1.SelectionFont = New Font(richTextBox1.Font, FontStyle.Bold)
count.RemoveAt(i)
Next
Catch
End Try
richTextBox1.[Select](richTextBox1.Text.Length, 0)
richTextBox1.SelectionFont = New Font(richTextBox1.Font, FontStyle.Regula
For each index select the text and make it bold.
Now add this code to the TextChanged-Event to check any time the text changed for your word.

I got it in a different way:
While Not RichTextBox1.Text.IndexOf("hello", startIndex) = -1
selectedIndex= RichTextBox1.SelectionStart
Try
RichTextBox1.Select(RichTextBox1.Text.IndexOf("test", startIndex) - 1, 1)
Catch
End Try
If RichTextBox1.SelectedText = " " Or RichTextBox1.SelectedText = Nothing Then
RichTextBox1.Select(RichTextBox1.Text.IndexOf("hello", startIndex) + "test".Length, 1)
If RichTextBox1.SelectedText = " " Or RichTextBox1.SelectedText = Nothing Then
RichTextBox1.Select(RichTextBox1.Text.IndexOf("hello", startIndex), "test".Length)
RichTextBox1.SelectionColor = Color.Blue
End If
End If
startIndex = RichTextBox1.Text.IndexOf("hello", startIndex) + "hello".Length
RichTextBox1.SelectionStart = selectedIndex
RichTextBox1.SelectionLength = 0
RichTextBox1.SelectionColor = Color.Black
End While
I don't know if it is the best way, but works.

That is a code for highlighting selected text at yellow (can be replaced by any other color), after finding it:
'find the text that need to be highlighted.
foundIndex = RichTextBox1.Find("hello", foundIndex + 1, -1, selectedFinds)
RichTextBox1.Focus()
If foundIndex = -1 Then
MessageBox.Show("This document don't contains the text you typed, or any of the text you typed as a whole word or mach case.", "Find Text Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
else
'now the text will be highlighted.
RichTextBox1.SelectionBackColor = Color.Yellow
Richtextbox1.focus
End If
I hope that code will help.

Private Sub RichTextBox1_DragOver(sender As Object, e As DragEventArgs) Handles RichTextBox1.DragOver
Dim p As Point
p.X = e.X
p.Y = e.Y
Dim num As Integer
Dim rightTXT As String
Dim leftTXT As String
Dim textpart As String
Dim TSelect As Boolean
Dim curpos As Integer = RichTextBox1.GetCharIndexFromPosition(RichTextBox1.PointToClient(p))
Dim PosStart As Integer
TSelect = False
If e.Data.GetDataPresent(DataFormats.StringFormat) Then
e.Effect = DragDropEffects.All
Try
leftTXT = Microsoft.VisualBasic.Left(RichTextBox1.Text, curpos)
If InStr(leftTXT, "%", CompareMethod.Text) Then
rightTXT = Microsoft.VisualBasic.Right(RichTextBox1.Text, Len(RichTextBox1.Text) - curpos)
If InStr(rightTXT, "%", CompareMethod.Text) Then
PosStart = curpos - InStr(StrReverse(leftTXT), "%") + 1
num = curpos + InStr(rightTXT, "%") - PosStart - 1
textpart = (RichTextBox1.Text.Substring(PosStart, num).TrimEnd)
Label3.Text = "mouse drag over:" + textpart
Label5.Text = num.ToString()
If ListBox1.Items.Contains(textpart) Then
TSelect = True
End If
End If
End If
Catch ex As Exception
Label4.Text = ex.ToString()
End Try
End If
If TSelect Then
Me.RichTextBox1.Select(PosStart - 1, num + 2)
wordSearch = RichTextBox1.SelectedText
Label4.Text = "word drag state: true"
match = True
Else
Label3.Text = "mouse drag over:"
Label4.Text = "word drag state: false"
Me.RichTextBox1.Select(0, 0)
End If
End Sub

I find the above codes to be too lengthy/complicated for a simple task...
Dim c As Integer = 0
Dim o As Integer = 0
Dim s As Integer = 0
Dim txt As String = RTB.Text
RTB.BackColor = Color.Black
Dim starts As Integer = 0
Do While txt.Contains(key) ' this avoids unnecessary loops
s = txt.IndexOf(key)
starts = s + o
RTB.Select(starts, key.Length)
RTB.SelectionBackColor = Color.Yellow
RTB.SelectionColor = Color.Blue
txt = txt.Substring(s + key.Length)
o += (s + key.Length)
c += 1
Loop
Me.Status.Text = c.ToString() & " found" ' and the number found

Related

Comparing text in two Richtextboxes and get the differences

I'm want to compare the text between two richtextboxes and get the differences in the third one. Without highlight the text.
So far, the best option is this solution
The first solution works, but it doesn't remove the text present in richtextbox2 from the richtextbox1.
Endeed, the user asked
if they are the same do nothing.
My case is complete the opposite and still i cannot find a solution.
Thanks
First, you need to add a combobox to your form named (combobox1)
then add these items in it:
RichTextbox1 - RichTextbox2
RichTextbox2 - RichTextbox1
second, add a button named (button1), under this button click event
insert this code:
RichTextBox3.Clear()
If RichTextBox1.Text <> "" And RichTextBox2.Text <> "" And RichTextBox1.Text <> RichTextBox2.Text And ComboBox1.SelectedItem = "RichTextbox1 - RichTextbox2" Then
Dim txt1(RichTextBox1.Text.Split(" ").Length) As String
Dim txt2(RichTextBox2.Text.Split(" ").Length) As String
txt1 = RichTextBox1.Text.Split(" ")
txt2 = RichTextBox2.Text.Split(" ")
Dim diff1 As String = ""
For Each diff As String In txt1
If Array.IndexOf(txt2, diff.ToString) = -1 Then
diff1 += diff.ToString & " "
End If
Next
RichTextBox3.Text = diff1.ToString
End If
If RichTextBox1.Text <> "" And RichTextBox2.Text <> "" And RichTextBox1.Text <> RichTextBox2.Text And ComboBox1.SelectedItem = "RichTextbox2 - RichTextbox1" Then
Dim txt1(RichTextBox1.Text.Split(" ").Length) As String
Dim txt2(RichTextBox2.Text.Split(" ").Length) As String
txt1 = RichTextBox1.Text.Split(" ")
txt2 = RichTextBox2.Text.Split(" ")
Dim diff2 As String = ""
For Each diff As String In txt2
If Array.IndexOf(txt1, diff.ToString) = -1 Then
diff2 += diff.ToString & " "
End If
Next
RichTextBox3.Text = diff2.ToString
End If
now, you have 2 options:
if you choose (RichTextbox1 - RichTextbox2) from the combobox then click the button, richtextbox3 will display the text which is found in richtextbox1 and not found in richtextbox2, while if you choose (RichTextbox2 - RichTextbox1), the opposite will happen
finally, if the 2 richtextboxes is the same, nothing will occur
Also you could use String.Join *
Under Button1 click event replace this code with the previous one:
Dim intsA = RichTextBox1.Text.Split(" ")
Dim intsB = RichTextBox2.Text.Split(" ")
Dim myresult = intsA.Except(intsB).ToArray()
RichTextBox3.Text = String.Join(" ", myresult)
if you found this useful, mark it as answer

Index was outside the bounds of the array. VB

I have been trying to create a program that will find the word the user has clicked on, in a multiline textbox. This procedure is based on the index from the position of the click. The code I implemented:
Public Class Form1
Private Sub TextBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles TextBox1.MouseDown
If e.Clicks = 1 And e.Button = MouseButtons.Left Then
'Try
Dim indexClicked As Integer = TextBox1.GetCharIndexFromPosition(New Point(e.X, e.Y))
Dim ch As Char = TextBox1.Text.Chars(indexClicked)
Dim indexOfWord As Int32
If Not ch = " " Then
Dim wordFound As Boolean
Dim previousCh As Char
Dim previousIndex As Integer = indexClicked
While Not wordFound
previousIndex = previousIndex - 1
previousCh = TextBox1.Text.Chars(previousIndex)
If previousCh = " " Then
indexOfWord = previousIndex + 1
wordFound = True
End If
End While
Else
indexOfWord = indexClicked + 1
End If
Label1.Text = indexClicked & ", " & indexOfWord
Label2.Text = GetWordByIndex(TextBox1.Text, indexOfWord)
' Catch ex As Exception
' Label2.Text = ex.Message
' End Try
End If
End Sub
Public Shared Function GetWordByIndex(input As String, index As Integer) As String
Try
Dim words = input.Split(" ")
If (index < 0) OrElse (index > words.Length - 1) Then
Throw New IndexOutOfRangeException("Index out of range!")
End If
Return words(index)
Catch ex As Exception
'handle the exception your way
Return String.Empty
End Try
End Function
End Class
The problem is that whenever the program reaches the line:
previousCh = TextBox1.Text.Chars(previousIndex)
it exits with :
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsApplication1.exe
Additional information: Index was outside the bounds of the array.
While the exception is thrown, by hovering over the previousIndex variable visual studio shows me its value: -1.
I think that previousCh = " " condition never gets true, so the program never exits the while loop, which keeps looking for the previous character. At some point int previousIndex gets negative and the program crashes. Why does not the condtion work properly?
What is the problem?
Thank you.
If you do not want to have the user double click like David Wilson suggested (which i would also agree with) then this will get the result you want. It takes into account if the previous character is a line feed or the start of the text, or the next character is a line feed or end of the text as well. You can add to the If to find "," or "." if needed.
Private Sub TextBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles TextBox1.MouseDown
If e.Clicks = 1 And e.Button = MouseButtons.Left Then
Dim startIndex As Integer = TextBox1.SelectionStart
Dim wordStartFound, wordEndFound As Boolean
Dim nextIndex, indexOfStartOfWord, indexOfEndOfWord, lengthOfWord As Integer
If Not startIndex = 0 Then
While Not wordStartFound
startIndex = startIndex - 1
If TextBox1.Text.Chars(startIndex) = " " Then
indexOfStartOfWord = startIndex + 1
wordStartFound = True
ElseIf startIndex = 0 Then
indexOfStartOfWord = startIndex
wordStartFound = True
ElseIf TextBox1.Text.Chars(startIndex) = Chr(10) Then 'Line Feed'
indexOfStartOfWord = startIndex + 1
wordStartFound = True
End If
End While
Else
indexOfStartOfWord = startIndex
End If
nextIndex = startIndex
While Not wordEndFound
nextIndex = nextIndex + 1
If TextBox1.Text.Chars(nextIndex) = " " Then
indexOfEndOfWord = nextIndex
wordEndFound = True
ElseIf nextIndex = TextBox1.TextLength - 1 Then
indexOfEndOfWord = TextBox1.TextLength
wordEndFound = True
ElseIf TextBox1.Text.Chars(nextIndex) = Chr(10) Then 'Line Feed'
indexOfEndOfWord = nextIndex
wordEndFound = True
End If
End While
lengthOfWord = indexOfEndOfWord - indexOfStartOfWord
Label2.Text = TextBox1.Text.Substring(indexOfStartOfWord, lengthOfWord)
End If
End Sub
Also in your function GetWordByIndex you split the input string into an array
Dim words = input.Split(" ")
then you say
If (index < 0) OrElse (index > words.Length - 1) Then
Throw New IndexOutOfRangeException("Index out of range!")
End If
but when you call .length on an array it returns the number of strings (or whatever is in the array) For example if the input was "The big brown fox jumped over the lazy dog", words.length - 1 will return 8. So if your index you pass through is the start of the word "over" it would fall into the Throw New IndexOutOfRangeException("Index out of range!") as the index would be 26 which is obviously greater than 8.
The code i have provided doesn't use the function to find the word but i thought i would mention that anyway.

How to make Hashtag highlighting in visual basic 2012

I want to highlight the text inside the text Box when a "#" is typed followed by any character as Facebook does. I tried to use SelectionStart ,SelectionLength and SelectionBackColor properties but I am facing many problems.
I need a help, what is the best event to handle the characters that are being typed? I used TextChanged event but its not working will. And is there another properties instead of SelectionStart and SelectionLength?
Please just give me tips and I will search.
I searched a lot but not finding useful topics.
Unfortunately, I don't think there is a way to do that with vb.net as it requires a postback to the server to run. In order to have it highlight the text as the user types you would need a frontend script to run.
Here is a link that may be helpful: https://forums.asp.net/t/1597892.aspx?Highlight+text+in+a+textbox
I made it !
Its working :) ...
This code detect hashtag entered by user and color it with green, also when the number of char exceed 140 it start highlighting them with red.
I used the KeyPress event instead of textChanged.
Public Class Form1
Dim previous As Char = " "
Dim indexOfHash As Integer = -1
Dim extraChar As Integer = 0
Private Const charLimit As Integer = 140 ' maximum char allowed in the textbox
Private Sub RichTextBox_keyPressed(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles RichTextBox.KeyPress
Try
Dim remainingCharCount As Integer
Dim textBoxLength As Integer = RichTextBox.TextLength
' if input is BACKSPACE
If (Not String.IsNullOrEmpty(e.KeyChar) AndAlso Asc(e.KeyChar) = 8) Then
remainingCharCount += 1
End If
remainingCharCount = charLimit - RichTextBox.TextLength
charRemainingLabel.Text = remainingCharCount & " Characters Left"
If remainingCharCount < 0 Then
extraChar += 1
Dim temp As Integer = RichTextBox.SelectionStart
RichTextBox.SelectionStart = RichTextBox.TextLength
RichTextBox.SelectionLength = remainingCharCount * -1
RichTextBox.SelectionBackColor = Color.LightCoral
RichTextBox.SelectionColor = Color.Black
charRemainingLabel.Text = String.Empty
charMinusLabel.Text = remainingCharCount & " Characters"
RichTextBox.SelectionStart = temp
ElseIf remainingCharCount >= 0 AndAlso extraChar > 0 Then
Dim temp As Integer = RichTextBox.SelectionStart
RichTextBox.SelectionStart = RichTextBox.TextLength
RichTextBox.SelectionLength = extraChar
RichTextBox.SelectionBackColor = Color.Transparent
RichTextBox.SelectionColor = Color.Black
RichTextBox.SelectionStart = temp
extraChar = 0
End If
Dim input As Char = e.KeyChar
Dim inputAsInteger As Integer = Asc(e.KeyChar)
previous = RichTextBox.GetCharFromPosition(RichTextBox.GetPositionFromCharIndex(RichTextBox.TextLength))
' if Hash and preceeded with SPACE or ENTER
If (Not String.IsNullOrEmpty(input) AndAlso input = "#" AndAlso (previous = " " Or String.IsNullOrEmpty(previous) Or previous = vbLf Or Asc(previous) = 13 Or RichTextBox.TextLength = 0)) Then
indexOfHash = RichTextBox.TextLength
End If
' if Hash exists STOP when find SPACE or ENTER
If indexOfHash <> -1 AndAlso (input = " " Or String.IsNullOrEmpty(input) Or Asc(input) = 13 Or input = vbLf) AndAlso (RichTextBox.TextLength - indexOfHash) > 1 Then
RichTextBox.SelectionStart = indexOfHash
RichTextBox.SelectionLength = RichTextBox.TextLength - indexOfHash
RichTextBox.SelectionColor = Color.Green
RichTextBox.SelectionStart = RichTextBox.TextLength
'RichTextBox.DeselectAll()
RichTextBox.SelectionColor = Color.Black
indexOfHash = -1 ' end of HashTag
End If
' if input is BACKSPACE
If (Not String.IsNullOrEmpty(input) AndAlso Asc(input) = 8 AndAlso (previous = "#")) Then
indexOfHash = RichTextBox.TextLength - 1
remainingCharCount += 1
End If
Catch ex As Exception
End Try
End Sub
end class

RichTextBox flikers when syntax highlight

I am writing an IDE an while working on syntax highlighting, i've encountered a very annoying issue.
When I type something, the text flickers...
Here is my code:
Dim KeyWords As List(Of String) = New List(Of String)(New String() {"void", "int", "long", "char", "short", "unsigned", "signed", "#include", "#define", "return"})
Dim KeyWordsColors As List(Of Color) = New List(Of Color)(New Color() {Color.Purple, Color.Purple, Color.Purple, Color.Purple, Color.Purple, Color.Purple, Color.Purple, Color.Olive, Color.Olive, Color.Blue})
Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
Dim words As IEnumerable(Of String) = RichTextBox1.Text.Split(New Char() {" "c, ".", ",", "?", "!", "(", Chr(13), Chr(10), " "})
Dim index As Integer = 0
Dim rtb As RichTextBox = sender 'to give normal color according to the base fore color
For Each word As String In words
'If the list contains the word, then color it specially. Else, color it normally
'Edit: Trim() is added such that it may guarantee the empty space after word does not cause error
coloringRTB(sender, index, word.Length, If(KeyWords.Contains(word.ToLower().Trim()) Or KeyWords.Contains("<"), KeyWordsColors(KeyWords.IndexOf(word.ToLower().Trim())), rtb.ForeColor))
index = index + word.Length + 1 '1 is for the whitespace, though Trimmed, original word.Length is still used to advance
Next
Dim strings() As String = RichTextBox1.Text.Split(Chr(34))
Dim count As Integer = 0
Dim cpart As Integer = 0
For Each part In strings
cpart = cpart + 1
If cpart Mod 2 = 0 Then
coloringRTB(RichTextBox1, count - 1, part.Length + 2, Color.Olive)
End If
count = count + part.Length + 1
Next
Dim strings2() As String = RichTextBox1.Text.Split(New Char() {"<", ">"})
count = 0
cpart = 0
For Each part In strings2
cpart = cpart + 1
If cpart Mod 2 = 0 Then
coloringRTB(RichTextBox1, count - 1, part.Length + 2, Color.Olive)
End If
count = count + part.Length + 1
Next
End Sub
Private Sub coloringRTB(rtb As RichTextBox, index As Integer, length As Integer, color As Color)
Dim selectionStartSave As Integer = rtb.SelectionStart 'to return this back to its original position
rtb.SelectionStart = index
rtb.SelectionLength = length
rtb.SelectionColor = color
rtb.SelectionLength = 0
rtb.SelectionStart = selectionStartSave
rtb.SelectionColor = rtb.ForeColor 'return back to the original color
End Sub
Private Sub RichTextBox1_KeyUp(sender As Object, e As KeyPressEventArgs) Handles RichTextBox1.KeyPress
If e.KeyChar = "{"c Then
RichTextBox1.SelectedText = "{}"
RichTextBox1.SelectionStart = RichTextBox1.Text.Substring(0, RichTextBox1.SelectionStart).LastIndexOf("{") + 1
e.Handled = True
End If
If e.KeyChar = "("c Then
RichTextBox1.SelectedText = "()"
RichTextBox1.SelectionStart = RichTextBox1.Text.Substring(0, RichTextBox1.SelectionStart).LastIndexOf("(") + 1
e.Handled = True
End If
If e.KeyChar = "["c Then
RichTextBox1.SelectedText = "[]"
RichTextBox1.SelectionStart = RichTextBox1.Text.Substring(0, RichTextBox1.SelectionStart).LastIndexOf("[") + 1
e.Handled = True
End If
If e.KeyChar = "'"c Then
RichTextBox1.SelectedText = "''"
RichTextBox1.SelectionStart = RichTextBox1.Text.Substring(0, RichTextBox1.SelectionStart).LastIndexOf("'")
e.Handled = True
End If
Dim currentLength = RichTextBox1.Text.Length
End Sub
hope someone can help Thanks ^_^
RichTextBox1 is the richtextbox

How to generate all combinations of partitioning a string in VB.Net

Given a string, how do you generate all partitions of it (shown as smaller strings separated by commas)?
Also, what is the total number of partitions for a string of length n?
The following will give the result, but is not good on long strings.
String: CODE
C,O,D,E
C,O,DE
C,OD,E
C,ODE
CO,D,E
CO,DE
COD,E
String: PEACE
P,E,A,C,E
P,E,A,CE
P,E,AC,E
P,E,ACE
P,EA,C,E
P,EA,CE
P,EAC,E
PE,A,C,E
PE,A,CE
PE,AC,E
PE,ACE
PEA,C,E
PEA,CE
Sub getAllComb()
oriStr = TextBox1.Text
Dim tmp = ""
Dim k = 0
For i = 0 To oriStr.Length
For j = 1 To 3
'tmp = Mid(oriStr, i, j)
Try
tmp1(k) = oriStr.Substring(i, j)
k = k + 1
'tmp = oriStr.Substring(i, j)
'Debug.Print(tmp)
Catch ex As Exception
'Debug.Print("Error>>>>" + ex.Message)
Exit For
End Try
Next
Next
tmp = ""
For i = 0 To k
Debug.Print(i.ToString + "<i " + tmp1(i))
tmp = tmp & tmp1(i) & vbCrLf
Next
'MessageBox.Show(tmp)
Dim tmpAll1 = ""
tmpAll1 = addFunclen4(k)
MessageBox.Show(tmpAll1)
Debug.Print(tmpAll1)
TextBox1.Text = oriStr & vbCrLf & vbCrLf & tmpAll1
End Sub
Function addFunclen4(k As Integer) As String
Dim retVal = ""
Dim tmp = ""
Dim tmpAll = ""
Dim tmpStr = ""
Dim tmpAll1 = ""
For i = 0 To k
For i1 = 0 To k
For i2 = 0 To k
For i3 = 0 To k
For i4 = 0 To k
tmp = Form1.tmp1(i) + Form1.tmp1(i1) + Form1.tmp1(i2) + Form1.tmp1(i3) + Form1.tmp1(i4)
If Form1.tmp1(i) <> "" Then
If tmp = Form1.oriStr Then
tmpStr = Form1.tmp1(i) + "," + Form1.tmp1(i1) + "," + Form1.tmp1(i2) + "," + Form1.tmp1(i3) + "," + Form1.tmp1(i4)
Do While tmpStr.Contains(",,") = True
tmpStr = Replace(tmpStr, ",,", ",")
Loop
If Mid(tmpStr, tmpStr.Length, 1) = "," Then
tmpStr = Mid(tmpStr, 1, tmpStr.Length - 1)
End If
If tmpAll1.Contains(tmpStr) = False Then
tmpAll1 = tmpAll1 + tmpStr + vbCrLf
End If
End If
End If
Next
Next
Next
Next
Next
retVal = tmpAll1
Return retVal
End Function
I reckon [2^(n-1) - 1] in total:
(n-1) positions to put a comma, 2 "states" (comma or not comma), -1 for the trivial case with no commas.
A simpler algorithm would be to iterate through the number of cases and use the binary representation to determine whether to put a comma in each position.
For example (simple form with TextBox, Button and ListBox):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
Dim s As String = TextBox1.Text
If s.Length < 2 Then
MessageBox.Show("Enter a longer string")
Return
End If
For i = 1 To Math.Pow(2, s.Length - 1) - 1
Dim result As String = s(0)
For j = 1 To s.Length - 1
result = result & CommaOrNot(i, j) & s(j)
Next
ListBox1.Items.Add(result)
Next
End Sub
Private Function CommaOrNot(i As Integer, j As Integer) As String
If (i And Math.Pow(2, j - 1)) = Math.Pow(2, j - 1) Then
Return ","
Else
Return ""
End If
End Function
I really liked Fruitbat's approach. Here's an alternate version using a slightly different mechanism for the representation of the binary number and how to determine if the comma should be included or not:
Public Class Form1
Private combinations As List(Of String)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim s As String = TextBox1.Text
If s.Length < 2 Then
MessageBox.Show("Enter a longer string")
Exit Sub
End If
Button1.Enabled = False
ListBox1.DataSource = Nothing
ListBox1.Items.Clear()
ListBox1.Items.Add("Generating combinations...")
BackgroundWorker1.RunWorkerAsync(s)
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim s As String = e.Argument
Dim combinations As New List(Of String)
Dim binary() As Char
Dim values() As Char = s.ToCharArray
Dim max As Integer = Convert.ToInt32(New String("1", s.Length - 1), 2)
Dim sb As New System.Text.StringBuilder
For i As Integer = 0 To max
sb.Clear()
binary = Convert.ToString(i, 2).PadLeft(values.Length, "0").ToCharArray
For j As Integer = 0 To values.Length - 1
sb.Append(If(binary(j) = "0", "", ","))
sb.Append(values(j))
Next
combinations.Add(sb.ToString)
Next
e.Result = combinations
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
combinations = e.Result
ListBox1.Items.Clear()
ListBox1.Items.Add("Generating combinations...Done!")
ListBox1.Items.Add("Adding Results...one moment please!")
Application.DoEvents()
ListBox1.DataSource = Nothing
ListBox1.DataSource = combinations
Button1.Enabled = True
MessageBox.Show("Done!")
End Sub
End Class