Skip to content

Listbox, How can I find item starting with example "be" doing keypress?

Sondre Garmo

Asked Aug 28, 2005, 12:27 PM EDT1 answer
Share
LinkedInX

Hallo!

If I have a listBox with 4 items (Beatles, Bruce Springsteen, Scooter, Eagles) and
press "b" in my listBox, SelectedItem will select the first item on "b".
If I press "be" in my listBox, It will select Eagles and not Beatles like Windows Explorer will do.

How can I press more characters and find the item with these characters?
I want my listBox to work like Windows Explorer does.


Example:
----------------------------

ListBox with follow items:
Beatles
Bruce Springsteen
Eagles
Scooter

Here is my wishes:
"b" = Beatles
"be" = Beatles
"br" = Bruce Springsteen
"e" = Eagles

--------------------------------------

Can somebody help me please?

Thanks

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    I found my own way to do this!

    You must have a ListBox on a form.
    Here is my code:



    C#
    public class Form1 : System.Windows.Forms.Form
    {
    // Textvariable to save the KeyPress characters.
    
    public string KeyPressSearch = "";
    
    // Timer to do the search in listBox.
    
    private System.Windows.Forms.Timer timKeyPressSearch;
    
    
    public Form1()
    {
    //
    // Required for Windows Form Designer support
    //
    InitializeComponent();
    
    }
    
    
    private void InitializeComponent()
    {
    
    this.timKeyPressSearch = new System.Windows.Forms.Timer();
    //
    // timKeyPressSearch
    //
    this.timKeyPressSearch.Enabled = false;
    this.timKeyPressSearch.Interval = 1000;
    this.timKeyPressSearch.Tick +=new EventHandler(timKeyPressSearch_Tick);
    
    }
    
    private void listBox1_KeyPress(object sender, KeyPressEventArgs e)
    {

    timKeyPressSearch.Enabled = true;

    C#
    e.Handled = true;
    
    KeyPressSearch = KeyPressSearch + e.KeyChar.ToString();
    
    }
    
    private void timKeyPressSearch_Tick(object sender, EventArgs e)
    {
    int index = listBox1.FindString(KeyPressSearch);
    KeyPressSearch = "";
    int oldIndex = listBox1.SelectedIndex;
    if (index != -1)
    {
    listBox1.SetSelected(index,true);
    timKeyPressSearch.Enabled = false;
    }
    else
    {
    listBox1.SetSelected(oldIndex,true);
    timKeyPressSearch.Enabled = false;
    }
    }
    0