Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

IntelliSense TextBox in C#

0.00/5 (No votes)
3 Mar 2014 1  
Auto Word Completion for Multiline Textbox (Minimal Intellisense)

Introduction

IntelliSense is nothing but a feature to predict the word when we are typing the starting letter of the word. We all are using Visual Studio, there we are typing the class name or namespace name, Visual Studio automatically shows the object list which holds the member & methods of that class / namespace.

This tip will definitely be useful to you to make your own IntelliSense TextBox in C#. This not a perfect IntelliSense but it has minimal ability to handle the auto word completion.

System Design

The system design of this application is very easily understandable. When we are entering text in TextBox, the popup listbox shows the list of starting letters of the last word in the string. The popup listbox items are loaded from the dictionary list which we created for the application. If the last word is not matching with list elements, the popup menu hides.

The popup menu should be shown the downside of the text line so here we need to get the text cursor position. For that, we need to call private extern static int GetCaretPos(out Point p) function of user32.dll assembly.

Using the Code

The AutoCompleteTextBox is the method for making IntelliSense for the given TextBox.

AutoCompleteTextBox Method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Windows.Forms;

namespace IntellisenceTextBox
{
    class clsIntelliSense
    {
        [DllImport("user32")]
        private extern static int GetCaretPos(out Point p);

        /// <summary>
        /// <para>AutoCompleteTextBox is the method to popups when typing the keywords on TextBox to avoid the mistakes.</para>
        /// <para>Type 1:</para>
        /// <para>&#160;&#160;&#160;&#160;List&lt;string&gt; 
        ISList = new List&lt;string&gt;(new string[] { "SELECT", "CREATE", "TABLE" }); </para>
        /// <para>&#160;&#160;&#160;&#160;AutoCompleteTextBox(textBox1,listBox1, ISList,e);</para>
        /// <para></para>
        /// <para>Type 2:</para>
        /// <para>&#160;&#160;&#160;&#160;AutoCompleteTextBox(textBox1,listBox1,
        new List&lt;string&gt;(new string[] { "SELECT", "CREATE", "TABLE" }),e);</para>
        /// <para></para>
        /// <para>Type 3:</para>
        /// <para>&#160;&#160;&#160;&#160;AutoCompleteTextBox(textBox1,listBox1,
        new string[] { "SELECT", "CREATE", "TABLE" }.ToList(),e);</para>
        /// <para>Note: Don't Use Two Words in Dictionary List. Ex. "AUDI CAR" </para>
        /// </summary>
        /// <param name="txtControl">Text Box Name</param>
        /// <param name="lstControl">List Box Name</param>
        /// <param name="lstAutoCompleteList">Dictionary List</param>
        /// <param name="txtControlKEA">Text Box Key Up Event Args.</param>
        /// 
        public static void AutoCompleteTextBox(TextBox txtControl, ListBox lstControl, 
            List<string> lstAutoCompleteList, KeyEventArgs txtControlKEA)
        {
            Point cp;
            GetCaretPos(out cp);
            List<string> lstTemp = new List<string>();
            //Positioning the Listbox on TextBox by Type Insertion Cursor position
            lstControl.SetBounds(cp.X + txtControl.Left, cp.Y + txtControl.Top + 20, 150, 50);

            var TempFilteredList = lstAutoCompleteList.Where
                (n => n.StartsWith(GetLastString(txtControl.Text).ToUpper())).Select(r => r);

            lstTemp = TempFilteredList.ToList<string>();
            if (lstTemp.Count != 0 && GetLastString(txtControl.Text) != "")
            {
                lstControl.DataSource = lstTemp;
                lstControl.Show();
            }
            else
            {
                lstControl.Hide();
            }

            //Code for focusing ListBox Items While Pressing Down and UP Key. 
            if (txtControlKEA.KeyCode == Keys.Down)
            {
                lstControl.SelectedIndex = 0;
                lstControl.Focus();
                txtControlKEA.Handled = true;
            }
            else if (txtControlKEA.KeyCode == Keys.Up)
            {
                lstControl.SelectedIndex = lstControl.Items.Count - 1;
                lstControl.Focus();
                txtControlKEA.Handled = true;
            }

            //text box key press event
            txtControl.KeyPress += (s, kpeArgs) =>
            {

                if (kpeArgs.KeyChar == (char)Keys.Enter)
                {
                    if (lstControl.Visible == true)
                    {
                        lstControl.Focus();
                    }
                    kpeArgs.Handled = true;
                }
                else if (kpeArgs.KeyChar == (char)Keys.Escape)
                {
                    lstControl.Visible = false;
                    kpeArgs.Handled = true;
                }
            };

            //listbox keyup event
            lstControl.KeyUp += (s, kueArgs) =>
            {
                if (kueArgs.KeyCode == Keys.Enter)
                {
                    string StrLS = GetLastString(txtControl.Text);
                    int LIOLS = txtControl.Text.LastIndexOf(StrLS);
                    string TempStr = txtControl.Text.Remove(LIOLS);
                    txtControl.Text = TempStr + ((ListBox)s).SelectedItem.ToString();
                    txtControl.Select(txtControl.Text.Length, 0);
                    txtControl.Focus();
                    lstControl.Hide();
                }
                else if (kueArgs.KeyCode == Keys.Escape)
                {
                    lstControl.Hide();
                    txtControl.Focus();
                }
            };
        }

        private static string GetLastString(string s)
        {
            string[] strArray = s.Split(' ');
            return strArray[strArray.Length - 1];
        }
    }
}

Calling the Method

The TextBox KeyUp Event is suitable for calling the above method. The following code is needed to be entered in the TextBox KeyUp Event.

txtInput.KeyUp += (s, e) => {
                List<string> DictionaryList = new List<string>(new string[] 
                { "AZEAL", "JOB", "INFO", "SOLUTIONS", 
                "CODE", "PROJECT", "FACEBOOK", "APPLE", 
                "MICROSOFT", "WINDOWS","SELECT","SET","COM"}.ToList());
                clsIntelliSense.AutoCompleteTextBox(txtInput, lstPopup, DictionaryList, e);
            }; 

Points of Interest

I figured this out while thinking about how Visual Studio's IntelliSense works.

History

This is preliminary. Later, we will think about the grammar & case sensitive listings to implement in this code.

Bug Fix: Listbox gets focus when pressing the up and down key on textbox while showing the listbox.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here