Home About

August 8th, 2009

C# Autosuggestion Textbox - 2

A few days ago I needed a textbox that automatically suggests common input options to the user. In my situation, names of companies. Because of screen space constraints I am unable to use a ComboBox (which already has this functionality).

The idea is that if the user enters one or more characters that the Textbox will search its list of suggestions. In this test implementation this is done through a simple List<>. Ultimately my list will contain many thousands of items and I will need to replace the List<> with a more efficient search algorithm.

In the below example code typing a single “W” will expand to “Waterland”, if you continue typing beyond the final “d” it will suggest “Waterland Investments”. Type a “T” and it will branch to “Waterland Telecommunication Systems”.

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Dijksterhuis.org
{
    class AutoSuggestControl : TextBox
    {
        List<string> Suggestions;
        int PreviousLength; 

        // V1.0 We are using a simple sorted list for the suggestions
        public AutoSuggestControl() : base()
        {
            Suggestions = new List<string>();

            // We keep track of the previous length of the string
            // If the user tries to delete characters we do not interfere
            PreviousLength = 0; 

            // Very basic list, too slow to be suitable for systems with many entries
            Suggestions.Add("Waterland");
            Suggestions.Add("Waterland Investments");
            Suggestions.Add("Waterland Telecommuncation Systems");
            Suggestions.Sort();
        }

        /// <summary>
        /// Search through the collection of suggestions for a match
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>

        private string FindSuggestion(string Input)
        {
            if (Input != "") 
            foreach (string Suggestion in Suggestions)
            {
                if (Suggestion.StartsWith(Input))
                    return Suggestion;
            }
            return null;
        }

        /// <summary>
        /// We only interfere after receiving the OnTextChanged event. 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);
          
            // We don't do anything if the user is trying to shorten the sentence
            int CursorPosition = SelectionStart;
            if (Text.Length > PreviousLength && CursorPosition >= 0)
            {
                string Suggestion = FindSuggestion(Text.Substring(0, CursorPosition));
                if (Suggestion != null)
                {
                    // Set the contents of the textbox to the suggestion
                    Text = Suggestion;
                    // Setting text puts the cursor at the beginning of the textbox, so we need to reposition it
                    Select(CursorPosition, 0);
                }
            }
            PreviousLength = Text.Length;
        }

  

    }
}

Be Sociable, Share!

Tags:

2 Responses to “C# Autosuggestion Textbox”

  1. Visual C# Kicks Says:

    Nice implementation and very useful code. I like that the search logic is encapsulated into a function which makes replacing the search algorithm easier. Thanks

  2. _daemon_ Says:

    You may look on textbox autocomplete feature:

    http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.autocompletesource.aspx
    http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.autocompletemode.aspx
    http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.autocompletecustomsource.aspx


Most popular
Recent Comments
  • ARS: great plugin! I love it! but, it will be so nice if you can add attribute ‘title’ as one of...
  • Nelson: Saved me from doing it myself. Good article.
  • andy: i am currently playing taiwanese server wow in 奈辛瓦里(PVP) and i would like to realm transfer to somewhere there...
  • berties: any english speaking playing on a taiwanese server?
  • web application development: has C# search volume really so constant over the years? really surprising.