Home About

 August 8th, 2009

C# Autosuggestion Textbox - 4

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;
        }

    }
}

Recent Comments
  • Ales: Hi, Thanks for the code… I must say I did not experience any errors decrypting any of my messages. I even...
  • JC: Thanks very useful and well explained
  • Thomas: This is a public static class written in the C# language that does not save state. You can call into the...
  • Simon: Thank you very much for this post! It helped me essentially to overcome obstacels to work with mono!
  • Graham: This is a good research for keyboard shortcuts! Some shortcuts are also compatible for Windows OS. I have...