Check if listbox contains textbox - vb.net

I know I could use .FindString for this but for some reason it is not working.
Basically,if listbox items contains just a PART of textbox text,it does action.
Here's the example of not-working code :
Dim x As Integer = -1
x = ListBox1.FindString(TextBox1.Text)
If x > -1 Then
'dont add
ListBox2.Items.Add("String found at " & x.ToString)
Else
End If

The FindString method returns the first item which starts with the search string (MSDN). If you want to match the whole item, you would have to use FindStringExact (MSDN). If you want to perform more complex searches, you would have to iterate through all the elements in the ListBox.
UPDATE:
Code delivering the exact functionality expected by the OP.
For i As Integer = 0 To ListBox1.Items.Count - 1
If (ListBox1.Items(i).ToString.Contains(TextBox1.Text)) Then
ListBox2.Items.Add("String found at " & (i + 1).ToString) 'Indexing is zero-based
Exit For
End If
Next

Related

Listbox.List(i) error - Method or Data Member not Found

I'm trying to use a multi-select listbox so users can select cleaning tasks they have completed and mark them as done. While looping through the list I want to see if the item is selected and create a record if so. When I try to use the .List method to return the data from a specific row, I keep getting the method not found error.
I originally did not have the forms 2.0 library loaded so I thought that was the issue, but that did not resolve the problem. I've also compacted and repaired thinking it might just be an odd fluke, but that did not help either.
'loop through values in listbox since its a multi-select
For i = 0 To listCleaningTasks.ListCount - 1
If listCleaningTasks.Selected(i) Then
'add entry to cleaning log
Set rsCleaning = CurrentDb.OpenRecordset("SELECT * FROM cleaning_log;")
With rsCleaning
.AddNew
.Fields("cleaning_task_id") = Form_frmCleaning.listCleaningTasks.List(i)
.Fields("employee_id") = Me.cmbUser
.Fields("cleanroom_id") = Me.cmbCleanroom
.Fields("cleaning_time") = Now()
.Update
.Close
End With
End If
Next i
Any ideas?
Use .listCleaningTasks.ItemData(r) to pull bound column value from row specified by index.
Use .listCleaningTasks.Column(c, r) to pull value specified by column and row indices.
Open and close recordset only one time, outside loop.
Really just need to loop through selected items, not the entire list.
Dim varItem As Variant
If Me.listCleaningTasks.ItemsSelected.Count <> 0 Then
Set rsCleaning = CurrentDb.OpenRecordset("SELECT * FROM cleaning_log")
With rsCleaning
For Each varItem In Me.listCleaningTasks.ItemsSelected
`your code to create record
...
.Fields("cleaning_task_ID") = Me.listCleaningTasks.ItemData(varItem)
...
Next
.Close
End With
Else
MsgBox "No items selected.", vbInformation
End If
Of course the solution of June7 is correct. If you need to store the selected items and then later recall and re-select the list box items, consider to get the selected items comma delimited using this function
Public Function GetSelectedItems(combo As ListBox) As String
Dim result As String, varItem As Variant
For Each varItem In combo.ItemsSelected
result = result & "," & combo.ItemData(varItem)
Next
GetSelectedItems = Mid(result, 2)
End Function
Store it into one column of a table and after reading it back pass it to this sub:
Public Sub CreateComboBoxSelections(combo As ListBox, selections As String)
Dim N As Integer, i As Integer
Dim selectionsArray() As String
selectionsArray = Split(selections, ",")
For i = LBound(selectionsArray) To UBound(selectionsArray)
With combo
For N = .ListCount - 1 To 0 Step -1
If .ItemData(N) = selectionsArray(i) Then
.Selected(N) = True
Exit For
End If
Next N
End With
Next i
End Sub
This will select items in your ListBox as they were before.

Wildcard Search character in vb.net

I am wanting to make a wildcard search character (ex. Binary%) so when they click search it finds all the files with the word Binary in the filename and loads them into a list box. My current code is below.
Private Sub _test_TextChanged(sender As Object, e As TextChangedEventArgs) Handles _test.TextChanged
For x As Integer = 0 To _listbox.Items.Count - 1
If _listbox.Items(x).ToString = _test.Text$ Then
_listbox.SelectedIndex = x
Return
End If
Next
End Sub
Any help is welcome!
Thank you!
-Kyvex
What you are asking doesn't really match your code.
... "when they click search it finds all the files" ...
But you have a TextChanged event handler of a TextBox (not a Button)
..."with the word Binary in the filename and loads them into a list box"
But you select only the first item which matches the filter of items already in a ListBox
To get your code to do what it seems to want to do, simply use the Like operator and add the wildcard character (*) after the TextBox.Text
For x As Integer = 0 To _listBox.Items.Count - 1
If _listBox.Items(x).ToString Like _test.Text & "*" Then
_listBox.SelectedIndex = x
Return
End If
Next
Now you can select the first item in the listbox which matches the filter
If you have a multi-select ListBox, you can use this
If _test.Text = "" Then Exit Sub
_listBox.SelectionMode = SelectionMode.MultiSimple
For x As Integer = 0 To _listBox.Items.Count - 1
_listBox.SetSelected(x, _listBox.Items(x).ToString Like _test.Text & "*")
Next
(the filter logic is the same as the first example)
And you can make it case-insensitive
_listBox.SetSelected(x, _listBox.Items(x).ToString().ToUpper() Like _test.Text.ToUpper() & "*")

Index out of range in listbox VB.NET

Consider the following code :
Private Sub DelButton_Click(sender As Object, e As EventArgs) Handles DelButton.Click
If OrderListBox.Text = "" = False Then
For i As Integer = OrderListBox.SelectedIndex To arr.Count - 1
arr.RemoveAt(i)
Next
OrderListBox.Items.Remove(OrderListBox.SelectedItem)
End If
calculate()
End Sub
The program crashes at arr.RemoveAt(i) and displays the following error:
Index was out of range. Must be non-negative and less than the size
of the collection.
First of all, please note that in VB.NET and C#, FOR loops are implemented differently!
In VB.NET, it works like this:
BEFORE the loop starts, you are determining start and end of the loop:
Start = OrderListBox.SelectedIndex
End = arr.Count-1
Then, the loop starts.
It is important to know, that in VB.NET, the end of the loop is NOT calculated again anymore. This is an important difference to C#. In C#, the end of the loop is calculated before each single loop.
And now, in the loop, you are DELETING records from the array.
Therefore, the count of records in the array is DECREASING.
However, your loop is going on, since you have calculated the count of records in the array before the loop started.
Therefore, you are going beyond the range of the array.
You could rewrite your code as follows:
Dim i as Integer
i = OrderListBox.SelectedIndex
while i < arr.Count
arr.RemoveAt(i)
Next
This article covers details about the for loop in VB.NET, especially the section "Technical Implementation": https://msdn.microsoft.com/en-us/library/5z06z1kb.aspx
This error will be thrown when you try to remove an item at an index greater than the size of the collection. i.e when i is greater than arr.Count - 1.
You should make sure that OrderListBox.SelectedIndex is not greater than arr.Count - 1. Because if it does, you remove an item that, well, does not exists.
This code is actually displayed in the MSDN docs. As stated, you should do something like this:
Private Sub RemoveTopItems()
' Determine if the currently selected item in the ListBox
' is the item displayed at the top in the ListBox.
If listBox1.TopIndex <> listBox1.SelectedIndex Then
' Make the currently selected item the top item in the ListBox.
listBox1.TopIndex = listBox1.SelectedIndex
End If
' Remove all items before the top item in the ListBox.
Dim x As Integer
For x = listBox1.SelectedIndex - 1 To 0 Step -1
listBox1.Items.RemoveAt(x)
Next x
' Clear all selections in the ListBox.
listBox1.ClearSelected()
End Sub 'RemoveTopItems
ListBox.SelectedIndex will return a value of negative one (-1) is returned if no item is selected.
You didn't check it in your code.
Change your code to this:
If OrderListBox.SelectedIndex >= 0 And OrderListBox.Text = "" = False Then
EDIT
Your code is this:
For i As Integer = OrderListBox.SelectedIndex To arr.Count - 1
arr.RemoveAt(i)
Next
Let's say your OrderListBox contains 3 items : [A, B, C] and the SelectedIndex is 0
Then your code will:
Remove (0) ===> [B, C]
Remove (1) ===> [B]
Remove (2) ===> Exception!
You need to reverse the loop
For i As Integer = arr.Count - 1 To OrderListBox.SelectedIndex Step -1
arr.RemoveAt(i)
Next

String.contains not working

I'm trying to filter a list based on input from a textbox. If the item doesn't contain the string, it is deleted from the list. Here is my subroutine:
Sub filterlists(filter As String)
Dim removalDifferential As Integer = 0
For colE As Integer = 0 To RadListView1.Items.Count
Try
Dim itemEpp As ListViewDataItem = Me.RadListView1.Items(colE)
Dim jobname As String = itemEpp(0)
If Not jobname.Contains(filter) Then
' MsgBox(jobname & " Contains " & filter)
RadListView1.Items.RemoveAt(colE - removalDifferential)
removalDifferential = removalDifferential + 1
End If
Catch
End Try
Next
End Sub
Currently this is not deleting the correct items. The TRY is there because when you delete an item the list index changes (which means the for loop length is wrong and will throw outofbounce errors). Any other loop options that will work here?
Assuming you really do want to delete any LVI which simply contains the filter text, you should loop backwards thru the items (any items, not just Listview items) so the index variable will in fact point to the next correct item after a deletion:
For n As Integer = RadListView1.Items.Count-1 to 0 Step -1
If radListView1.Items(n).Text.Contains(filter) Then
RadListView1.Items.RemoveAt(n)
End If
Next

RichTextBox Highlighting

Goal
Programmatically highlight part of a string contained in a RichTextBox based on what is selected in a DataGridView.
See screenshot for a more visual example
As you can see, when an Option type (EC - Electrical) is selected, its options are displayed in another DataGridView to the right. From there, the user can check the ones he wishes to have included in the Conveyor Function Summary (Photoeye in this case) and it gets highlighted.
Code Used
This method is executed every time the Option Type DataGridView has a selectionchanged event.
Private Sub SummaryOptionsHighlight()
Dim strToFind As String = ""
Dim textEnd As Integer = rtbSummary.TextLength
Dim index As Integer = 0
Dim lastIndex As Integer = 0
'Builds the string to find based on custom classes - works fine
For Each o As clsConveyorFunctionOptions In lst_Options
If o.Included Then
If strToFind.Length <> 0 Then strToFind += ", "
If o.Optn.IsMultipleQty And o.Qty > 0 Then
strToFind += o.Optn.Description & " (" & o.Qty & "x)"
Else
strToFind += o.Optn.Description
End If
End If
Next
'Retrieves the last index of the found string: ex. Photoeye (3x)
lastIndex = rtbSummary.Text.LastIndexOf(strToFind)
'Find and set the selection back color of the RichTextBox
While index < lastIndex
rtbSummary.Find(strToFind, index, textEnd, RichTextBoxFinds.None)
rtbSummary.SelectionBackColor = SystemColors.Highlight
index = rtbSummary.Text.IndexOf(strToFind, index) + 1
End While
End Sub
Problem
What's going on isn't a highlight but more of a backcolor being set to that selection. The reason I say this is because when I click in the RichTextBox to indicate that it has focus, it doesn't clear the highlighting. Perhaps there is an actual highlight instead of a backcolor selection?
See the difference:
Selection Back Color:
Highlighting:
to highlight, you just need to do this:
if richtextbox1.text.contians("photoeye") then
richtextbox1.select("photoeye")
end if
this should work for what you are trying to do