Highlight sets of matches within textbox - vb.net

Upon first inspection, I surmised this would be a straightforward task (maybe it still is!), yet I am having difficulty. Suppose I have a form with 1000 textboxes, where each textbox contains randomly distributed, yet in many cases matching strings. For example, the below may be found in any one if the 1000 textboxes:
AAAA-XXXX
AAAA-XXXX
BBBB-XXXX
BBBB-XXXX
CCCC-XXXX
CCCC-XXXX
...
How might I loop through the textboxes, identify all the matching examples and highlight the textbox.backcolor where the matches occur? The backcolor should be the same for the exact matches, yet different for each unique set of matches. There could be as many as 100 different sets!

Just whipped together a working test project, this is the kind of approach I'd take. It avoids comparing every textbox to every other textbox. I've commented it all up for you :)
Private Sub SetBoxColors()
'The keys are textbox texts, the values are the number of times it occurs
Dim UniqueTextsAndUsage As New Dictionary(Of String, Integer)
Dim FirstInstanceTextBoxes As New List(Of TextBox)
'The keys are textbox texts, the values are the colour for the box
Dim UniqueColors As New Dictionary(Of String, System.Drawing.Color)
'Iterate over all the text boxes
' Substitute Me for your Form instance if necessary
For Each TBox As Control In Me.Controls
'Skip things that aren't textboxes
If Not TypeOf TBox Is TextBox Then
Continue For
End If
'If we have seen this textbox text before
If UniqueTextsAndUsage.ContainsKey(TBox.Text) Then
'Increase the usage
UniqueTextsAndUsage(TBox.Text) += 1
If UniqueTextsAndUsage(TBox.Text) = 2 Then
'This is the second usage, generate a colour for this set of boxes
UniqueColors.Add(TBox.Text, GenerateColor(UniqueColors.Count + 1))
End If
'Colour this textbox
' (it won't get the first instance of each unique string)
TBox.BackColor = UniqueColors(TBox.Text)
Else
'We have NOT seen this textbox text before
'Add the first occurence of the text
UniqueTextsAndUsage.Add(TBox.Text, 1)
'Mark this textbox as one we may have to colour later
FirstInstanceTextBoxes.Add(TBox)
End If
Next
'Colour all the first instances
For Each TBox As TextBox In FirstInstanceTextBoxes
'Check there are sufficient uses of this text
If UniqueTextsAndUsage(TBox.Text) > 1 Then
TBox.BackColor = UniqueColors(TBox.Text)
End If
Next
End Sub
Private Function GenerateColor(Id As Integer) As System.Drawing.Color
'Needs more thought - often too dark
Dim KnownColourByIdNumber As System.Drawing.KnownColor = Id
Return System.Drawing.Color.FromKnownColor(KnownColourByIdNumber)
End Function
The GenerateColor function needs more thought so that it generates some nicer colours but I leave that to you.
You may also need a reset that sets every box to the DefaultControl color or whatever it's called, and run that at the top of SetBoxColors.

You can do this
Dim strText As String
For Each TextBox1 As System.Windows.Forms.TextBox In Me.Controls
strText = TextBox1.Text
For Each TextBox2 As System.Windows.Forms.TextBox In Me.Controls
If strText = TextBox2.Text AndAlso TextBox2.Name <> TextBox1.Name Then
TextBox2.BackColor = Color.Red ' or whatever you want to use
TextBox1.BackColor = Color.Red
End If
Next
Next

Related

VB DropDown Read Only

I have a DropDown and a DropDownList on my form. I am aware that a DropDown can hold a placeholder text and a DropDownList cannot, however; I would like some code or a work around to allow either:
DropDown as read-only, therefore not allowing a user to type
But preferably a DropDownList with placeholder text (context menu option, or not)
Is this possible?
Thanks.
But preferably a DropDownList with placeholder text (context menu option, or not)
By definition, the text displayed in this control is always the text of the selected item. You can add a "fake" item to the list if you want (e.g. "Select Property Code"), but you will have to check that this item isn't selected later.
To display one of the items (fake or not), simply set the SelectedIndex to the appropriate value once the list is loaded.
DropDown as read-only, therefore not allowing a user to type
This will actively make sure that the text is either in the list or a default value, effectively making it read only. (Written for a ComboBox, but the behavior should be identical with a DropDown.)
Private Sub ComboBox1_TextChanged(sender As Object, e As EventArgs) Handles ComboBox1.TextChanged
Static recursion As Boolean = False
Dim defaultText As String = "My Default Text"
If recursion Then
recursion = False
Else
If ComboBox1.Items.Count > 0 Then
For i As Integer = 0 To ComboBox1.Items.Count - 1
If ComboBox1.Items(i).ToString = ComboBox1.Text Then
Exit Sub
End If
Next
recursion = True
ComboBox1.Text = defaultText
End If
End Sub
Alternatively, here is a sub I call whenever a "strict" ComboBox looses focus to accomplish the same thing. The difference is that doing it this way allows you to keep the AutoComplete functionality:
Public Sub EnforceList(ByRef box As ComboBox) 'FORCES .TEXT TO BEST (OR FIRST) MATCH IN .ITEMS
'If list contains item whose name begins another item's, the shorter must be listed first, e.g. "sew" must preceed "sewer"
If box.Items.Count = 0 Then Exit Sub 'Can't enforce a list that doesn't exist
Dim txt As String = box.Text
Do
For i As Integer = 0 To box.Items.Count - 1
If box.Items(i).ToString Like txt & "*" Then
box.Text = box.Items(i).ToString
Exit Sub
End If
Next
txt = Left(txt, Len(txt) - 1)
Loop
End Sub

Is there a way to find the length of several variables at the same time?

I am trying to detect empty text boxes when a button is pressed. To do so I am using an if statement for each variable like so:
If Len(variable.Text) = 0 Then
Messagebox.Show("please fill in all fields.")
End If
Is there a more efficient way where I can detect if the lengths of the strings within all the text boxes are equal to zero at the same time? Or if anyone wants to suggest a better method that would also be appreciated. Thanks.
This would do, assuming the textboxes are in the same form as of the validation button
Dim ctrl As Control
For Each ctrl In Me.Controls ' panelname.controls etc
If (ctrl.GetType() Is GetType(TextBox)) Then
If Trim(ctrl.Text) = "" Then
MessageBox.Show("please fill in all fields.")
Exit Sub
End If
End If
Next
OR
Dim ctrl As Control
Dim count As Integer
count = 0
For Each ctrl In Me.Controls ' panelname.controls etc
If (ctrl.GetType() Is GetType(TextBox)) Then
If Trim(ctrl.Text) = "" Then count += 1
'you can add exceptions by textbox name also by getting ctrl.Name
End If
Next
If count > 0 Then
MessageBox.Show("please fill in all fields.")
End If
That's the way to go. (:
If you want to check if all textboxes are empty (or in other words: is it possible to leave some textboxes empty or not) you could use something like this:
'if some textboxes can be empty
IF a="" AND b="" AND c="" Then Messagebox.Show("please fill in all fields.")
'if no textbox can be empty
IF a="" OR b="" OR c="" Then Messagebox.Show("please fill in all fields.")

Manipulating ListBoxes as Objects

I am working on a VBA userform that includes ListBoxes.
So far, when I had to manipulate one or more, I always proceeded like this in my subs, with dlg as the dialogbox name, and it did not pose any problem, given that I never wanted to do anything complicated:
Dim List1 As Object
...
List1 = dlg.GetControl("CBXname")
...
List1.addItem("String",index)
...
Now I would like to do the following in this Sub
...
If (List1.Exists(Cell1.String) = False) Then
List1.addItem(Cell1.String,k)
End If
...
List1.Clear
...
But I can do neither since List1 is an Object. However, if I decide to declare List1 as a Listbox instead, I do not know how to get the proper control on the ListBox from the dialogbox (the current getcontrol gives me an error).
One of the issues with your code is that listbox objects do not have an "exists" property. To check if a value already exists in your listbox items, you will need to loop through the items.
dim i as integer
for i = 0 to List1.listcount - 1
if List1.column(0, i) = myvalue then
'myvalue exists in List1, skip
else
List1.additem myvalue
end if
next i
Where myvalue is whatever value you are trying to add to the listbox. But that brings us to the second issue in your code which is where you add "Cell1.String". If you are trying to add a value from a worksheet range you will need to refer to that range's value, as worksheet ranges do not have a "string" property as you use it here. Ie. Cell1 = Range("A1").value
As for getting control of the listbox, you can simply refer to the objects name as an object of the form. For example, dlg.List1, if the object's name is List1.
Here is a general purpose routine you can call for any list box. The calling code assumes a list box called ListBox1, a text box called TextBox1, and a Command Button called CommandButton. When you click on the button, it searches the listbox for the text from textbox1.
Private Function ExistsInListbox(ByRef aListBox As msforms.ListBox, ByVal Item As String) As Boolean
Dim booFound As Boolean
booFound = False
Dim t As Integer
ExistsInListbox = False
For t = 0 To aListBox.ListCount - 1 'correction, aListBox not ListBox1
If Item = aListBox.List(t) Then
'if we find a match, short-circuit the loop
booFound = True
Exit For
End If
Next
ExistsInListbox = booFound
End Function
private sub CommandButton_click()
Dim answer As String
Dim val As Boolean
val = ExistsInListbox(Me.ListBox1, TextBox1.Text)
If val Then
answer = "found"
Else
answer = "Not Found"
End If
MsgBox "found-" & answer
End Sub

Delete multiple textboxes from list of controls

I have a list of controls created dynamically in a control list. The user has options to add textboxes in the control list and to delete them as well.
I have created the textboxes using the following code:
Dim tb As New TextBox
tb.Name = "Textbox" & counter.ToString
tb.Left = 55
tb.Top = fields
Me.Controls.Add(tb)
MyControls.Add(tb)
counter = counter + 1
So, the textbox names when created are Textbox1, Textbox2 and so on maximum up to Textbox10.
The user can delete textboxes by button clicks one by one. If the user wants to delete these textboxes, counter will run backward and will delete Textbox10 first and then Textbox9 and so on (This is the same as First in First Out).
So, for deleting I tried the following code, but it didn't execute, giving an error. The code is written under Button's Click event of the delete button.
For Each CType(Me.Controls("Textbox" & counter), TextBox) As Control In MyControls
Me.Controls.Remove(...) 'The textbox's name to be deleted in place of dots
'The textbox name to be deleted here with .Dispose()
Next
The error is: "Expression is a value and therefore cannot be the target of an assignment" in the first line of the above code.
How to delete a series of textboxes dynamically?
This line is causing the problem:
For Each CType(Me.Controls("Textbox" & counter), TextBox) As Control In MyControls
CType(Me.Controls("Textbox" & counter), TextBox) resolves to a value, so it cannot be a loop increment variable.
To delete based on a loop, you would need to know how many controls you want to delete. Here is one way:
For i As Integer = 1 To Math.Min(NumberOfControlsToDelete, 10) ' Cap deleting at 10.
' Make sure we don't go below 1.
If counter < 1 Then Continue
' Expected that the control will exist.
Me.Controls.Remove(Controls.Find("TextBox" & counter, True)(0))
' Decrement counter.
counter -= 1
Next
It looks like you're already keeping track of those dynamic buttons by adding them to a List? in this line (your 6th line of code):
MyControls.Add(tb)
As such, simply grab the last entry and remove it, no need to go searching for the control by name:
If MyControls.Count > 0 Then
Dim TB As TextBox = MyControls(MyControls.Count - 1)
MyControls.Remove(TB)
TB.Dispose()
End If
If you want to delete all of them at the same time:
For Each TB As TextBox In MyControls
TB.Dispose()
Next
MyControls.Clear()
Is this what you're looking for? I'm not sure I'm reading your question correctly.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Controls.Remove(Me.Controls.Find(""Textbox" & counter"))
End Sub

VB Avoiding text box that is occupied

I am making an application where there is a form with a column of text boxes that are filled from two different forms with a button on each. when the button of these forms are clicked they input the results into the text boxes in the column.
the problem I am having is that say i click (form2.button 1) three times it will occupy text boxes 1,2 and 3. Now say I want to use (form1.button 1) to input data into text box 4 it will occupy text box 1.
I have each button set up for multiple clicks so I would like to understand how i can have is so say(form2.button 1) is clicked then (form1.button1) will go to 2nd click for example. there are 10 text boxes so I will need it so that they react to how many times each has been clicked.
Assuming the TextBoxes were called TextBox1 thru TextBox10, you could use a sub like this:
Public Sub AddValue(ByVal value As String)
For i As Integer = 1 To 10
Dim tbName As String = "TextBox" & i
Dim matches() As Control = Me.Controls.Find(tbName, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is TextBox Then
Dim tb As TextBox = DirectCast(matches(0), TextBox)
If tb.Text.Trim.Length = 0 Then
tb.Text = value
Exit Sub
End If
End If
Next
MessageBox.Show("All TextBoxes are already taken!")
End Sub
Why not just store a counter variable in the form that contains the textboxes, say NextTextBoxNumber that increments each time a textbox is filled in and then you know exactly which textbox to go to next based upon the value of this variable?
Also, to continue with #Oded's comment, you can easily accomplish what he meant using something along the lines of If Textbox1.Text <> "" Then ...
Does that make sense??