|
-
Sep 23rd, 2002, 05:58 PM
#1
Thread Starter
Member
Sorting through a list box
Here's the situation, I have a listbox that contains names in this format "last name, first name". I also have a textbox that the user types can type a string to pull up the appropiate name, i.e. if the user types in "S" I want the listbox to move to the "S" section, or even better only display names that start with "S".
"Smith, Ro" would bring up "Smith, Robert" (or any other Smith with a first name that starts with "Ro". I'm not sure how I can accomplish this and not kill program response time. The listbox could contain any number of items (probably less than 100, but upwards of 100 is possible.
Another question, how many items can a listbox hold without a serious slow down in response time?
-
Sep 23rd, 2002, 08:21 PM
#2
It seems like there should be some form of intrinsic way to do this, but I only found how to find an exact match (of course I didn't look THAT hard). But if you don't find one then this works just fine:
VB Code:
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'make an array and fill listbox
Dim items() As String = {"Marquez, Ed", "Marcus, Allen", "Sarver, Mike", "Doran, Cookie", "Dorn, Mike"}
ListBox1.Items.AddRange(items)
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
'convert listbox item to string array and pass to function
Dim itms(ListBox1.Items.Count - 1) As String
ListBox1.Items.CopyTo(itms, 0)
ListBox1.SelectedIndex= ClosestIndexOf(TextBox1.Text, itms, False)
End Sub
Private Function ClosestIndexOf(ByVal Text As String, ByVal Items() As String, Optional ByVal CaseSensitive As Boolean = True) As Integer
'returns -1 if no match at all is found
Dim itm As String
Dim found As Integer = -1
For Each itm In Items
If CaseSensitive Then
If itm.StartsWith(Text) Then
found = Array.IndexOf(Items, itm)
Exit For
End If
Else
'make both lower case before testing
Dim tmp As String = itm.ToLower
If tmp.StartsWith(Text.ToLower) Then
found = Array.IndexOf(Items, itm)
Exit For
End If
End If
Next
Return found
End Function
-
Sep 23rd, 2002, 09:45 PM
#3
Thread Starter
Member
thanks
Thank You!
Actually it is finding the closest match, i.e. Smi would go to Smith. Thanks for the code sample.
-
Sep 23rd, 2002, 10:52 PM
#4
Yeah I wrote that because I figured it'd come in handy for me too at some point, but the intrinsic IndexOf function will find an exact match if you need that.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|