Solved

visual studio vb.net key up find method

Posted on 2016-07-14
8
27 Views
Last Modified: 2016-07-15
I am using the following code so that I can find words quickly but I am finding that is making the sub string selections so if I want to find bhp i go B then h then p so not only does bhp enter into the selected items so does the letter B and h.

Can the method be altered so that it finds the words but I make the selection at the end? I didnt write this code I did some searches on google and found it

 Private Sub ListCW_KeyUp(sender As Object, e As KeyEventArgs) Handles ListCW.KeyUp
        Static SearchPattern As String
        SearchPattern &= CStr(Convert.ToChar(e.KeyValue))

        Dim FindIndex As Integer =
            sender.FindString(SearchPattern)

        If FindIndex = -1 Then
            SearchPattern = CStr(Convert.ToChar(e.KeyValue))
            sender.SelectedIndex = sender.FindString(SearchPattern)

        Else
            sender.SelectedIndex = FindIndex

        End If
    End Sub

Open in new window

0
Comment
Question by:PeterBaileyUk
  • 4
  • 4
8 Comments
 
LVL 32

Expert Comment

by:it_saige
ID: 41710982
By "at the end", I assume you mean after the user finishes typing?  If this is the case, then you want to perform the search when the text entry field loses focus (LostFocus) or is left (Leave).

-saige-
0
 

Author Comment

by:PeterBaileyUk
ID: 41710997
yes after they finish typing, so the code doesnt need to change it just goes into a different event?
0
 
LVL 32

Expert Comment

by:it_saige
ID: 41711004
Correct

Edit:  Actually the code would change since you would no longer be capturing the key as a part of the event.  Instead you would use the text from the sender.  Since sender is an object, you would cast sender to the type that raise the event; e.g. TextBox.

-saige-
0
 

Author Comment

by:PeterBaileyUk
ID: 41711011
I tried leave but it didnt like the argument and i dont think the listbox has a lost focus.
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 32

Accepted Solution

by:
it_saige earned 500 total points
ID: 41711221
If I'm being honest, using a ListBox in this way seems, a bit, impractical.  First, the listbox's type-ahead feature is meant to locate matching entries quickly.  Second, the listbox's type-ahead feature (as with other controls of this type; e.g. - TreeView, ListView, etc.) don't allow for correcting the search.  And finally, the type-ahead's primary function is to ease item selection, not finalize item(s) selection.

That being said, perhaps we can provide a work around.  Think of forwarding the key inputs to a textbox.  When enter is pressed the item is selected from the listbox and the textbox is cleared.  The user can also choose to type directly into the text box and press enter, thus selecting an item from the listbox or correcting a type-ahead mistake.

Let's see if we can make something like this work.

Form1.vb -
Public Class Form1

	Private Sub OnLoad(sender As Object, e As EventArgs) Handles MyBase.Load
		ListBox1.Items.AddRange(New Object() {"Peter", "Susan", "Sally", "Joseph", "Mary", "Michelle", "Malcom"})
	End Sub

	Private Sub OnKeyUp(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyUp, ListBox1.KeyUp
		Dim index = -1
		If TypeOf sender Is TextBox Then
			Dim tb = DirectCast(sender, TextBox)
			If tb.Equals(TextBox1) Then
				If e.KeyCode.Equals(Keys.Enter) Then
					index = ListBox1.FindString(tb.Text)
					If index <> -1 Then
						ListBox1.SetSelected(index, True)
					End If
					tb.Clear()
					e.Handled = True
				End If
			End If
		ElseIf TypeOf sender Is ListBox Then
			Dim lb = DirectCast(sender, ListBox)
			If lb.Equals(ListBox1) Then
				If e.KeyCode.Equals(Keys.Enter) Then
					index = lb.FindString(TextBox1.Text)
					If index <> -1 Then
						lb.SetSelected(index, True)
					End If
					TextBox1.Clear()
					e.Handled = True
				ElseIf e.KeyCode.Equals(Keys.Back) Then
					If TextBox1.Text.Length > 0 Then
						TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1)
					End If
				Else
					TextBox1.Text = TextBox1.Text + Convert.ToChar(e.KeyCode)
				End If
			End If
		End If
	End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
		Me.Label1 = New System.Windows.Forms.Label()
		Me.TextBox1 = New System.Windows.Forms.TextBox()
		Me.ListBox1 = New System.Windows.Forms.ListBox()
		Me.SuspendLayout()
		'
		'Label1
		'
		Me.Label1.AutoSize = True
		Me.Label1.Location = New System.Drawing.Point(13, 13)
		Me.Label1.Name = "Label1"
		Me.Label1.Size = New System.Drawing.Size(44, 13)
		Me.Label1.TabIndex = 0
		Me.Label1.Text = "Search:"
		'
		'TextBox1
		'
		Me.TextBox1.Location = New System.Drawing.Point(63, 10)
		Me.TextBox1.Name = "TextBox1"
		Me.TextBox1.Size = New System.Drawing.Size(209, 20)
		Me.TextBox1.TabIndex = 1
		'
		'ListBox1
		'
		Me.ListBox1.FormattingEnabled = True
		Me.ListBox1.Location = New System.Drawing.Point(63, 37)
		Me.ListBox1.Name = "ListBox1"
		Me.ListBox1.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple
		Me.ListBox1.Size = New System.Drawing.Size(209, 212)
		Me.ListBox1.TabIndex = 2
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(284, 261)
		Me.Controls.Add(Me.ListBox1)
		Me.Controls.Add(Me.TextBox1)
		Me.Controls.Add(Me.Label1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		Me.ResumeLayout(False)
		Me.PerformLayout()

	End Sub
	Friend WithEvents Label1 As System.Windows.Forms.Label
	Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
	Friend WithEvents ListBox1 As System.Windows.Forms.ListBox

End Class

Open in new window

Produces the following output -

Initial Load:Capture.JPGType "ma" in the textbox and press enter:Capture.JPGSelect the listbox and type "pe":Capture.JPGPress enter and viola:Capture.JPGIs it perfect and flawless, probably not, there may be some edge cases that I did not consider.

Tabbing, for instance, isn't taken into account.  Let me know what you think.

-saige-
0
 

Author Comment

by:PeterBaileyUk
ID: 41711816
I shall play with that suggestion, would you have used a better type of container more suited to what i am doing? is there one? the data in the listbox is pulled from an sqlserver table but i think you know that already.
0
 

Author Closing Comment

by:PeterBaileyUk
ID: 41711840
Thank you
0
 
LVL 32

Expert Comment

by:it_saige
ID: 41713558
Glad that I can provide assistance.

To answer your question about a better container.  The closest "out-of-the-box" control that I can think of is a combo-box that utilizes an auto-complete feature.  From a visual perspective, however, your items are really only visible when you have the drop-down opened.

-saige-
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now