Stone Stone -4 years ago 124 Question

List-box Search function

Please forgive me in advance for such messy code, as I'm still learning. However from the below screen shot I've got a search field, list-box and some pseudo data (Not actual data as that is sensitive)

Screen Shot of Controls

The way I handle the search currently is, if the value is an exact match, within a sub string, then the search field transitions from the colour white to the colour green. What I've been trying to do is when this happens the lstBox control will then select the line, which it does, but it will not scroll to the point in which the line is located. Could someone please point me in the right direction please. My scruffy code is below:

Sub searchRecord()
If txtSearch.Text <> "" And txtSearch.Text.Length = 10 Then
For i As Integer = 0 To lstLine.Items.Count - 1
If lstLine.Items(i).ToUpper.Substring(0, 10).Contains(txtSearch.Text.ToUpper) Then
lstLine.SelectedIndex = i
Exit For
End If
End If
End Sub

And please any criticism is welcome either about this post or my code, it's the only way I'm gonna learn.

Many Thanks in advance gents/ladies

Answer Source

I think you should use BringIntoView() method. In C# I would do it like this:

1) Get ListBoxItem from your SelectedItem

ListBoxItem selectedListBoxItem = lstLine.ItemContainerGenerator.ContainerFromItem(lstLine.SelectedItem) as ListBoxItem;

2) Then bring selected item into view:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download