Click here to Skip to main content
Click here to Skip to main content
Go to top

IntelliSense TextBox in C#

, 3 Mar 2014
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Anand Gunasekaran
Software Developer Azeal Groups
India India
My work and hobbies are developing software programs. I have worked in several software application development process. From my point of view, if we know the logic and creativity we can develop any software application in any programming language.
 
Technologies: .Net, Java, Php, Phython, Android, HTML
 
My Next Contributions will be Network Ace Game.
 
Willing to work in Malaysia.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 5 Pinprofessional Jas 2415-Mar-14 1:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 3 Mar 2014
Article Copyright 2014 by Anand Gunasekaran
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid