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

Creating AutoComplete HTML Tags in C#

0.00/5 (No votes)
1 May 2016 1  
In this article we will automatically close the HTML tags when starting tag is typed in RichTextBox in C#
Download Source Code


Introduction

Nowdays,almost in all advanced HTML,PHP,JavaScript,Perl etc. editors support automatically closing HTML tags feature.
Visual Studio provides rich built feature like automatically closing tags with AutoCompletion(Code Completion).
In this article, we will create automatically completing the HTML tags.
Download the source code to view simple and advanced HTML tags completion.

Procedure

Step 1 : Create Windows Forms Application in C#.
Step 2 : Drag & Drop RichTextBox onto that Form.
Step 3 : Add KeyPress & KeyDown events to RichTextBox.

Using the code

First declare the variables :

public static String EnteredString = "";
public static Boolean Is_LessThanKeyPressed = false;
public static Boolean Is_GreaterThanKeyPressed = false;
public static Boolean Is_AutoCompleteCharacterPressed = false;
public Boolean Is_SpaceBarKeyPressed = false;
public Boolean Is_TagClosedKeyPressed = false;

 

EnteredString : String variable to hold typed characters in RichTextBox.        
Is_LessThanKeyPressed : The value is set to true when "<" key is pressed,because HTML tag starts with "<"(e.g.: <html )
Is_GreaterThanKeyPressed : The value is set to true when ">" key is pressed,when ">" key is pressed,
                        i)  Select the current index from RichTextBox.
                        ii) Insert proper closing tags associated with starting tag at current index position.
Is_AutoCompleteCharacterPressed : The value is set to true when auto complete character is pressed like( ",',[,( ) for performing AutoCompleteBrackets feature.
Is_SpaceBarKeyPressed : The value is set to true when Space key is down.This variable is used to complete html tags even if space bar key is pressed.We press the space bar key to add attributes to given html tag,so to complete this tag,we need this variable.
Is_TagClosedKeyPressed : The value is set to true when html tag is completed by user not automatically or when auto completion feature fails then user must end the tag,when he ends then tag by pressing ">" key then that tag must not be completed again.                        

               
Declare the array list of html tags :

public String[] tagslist ={
    "html",
    "head",
    "title",
    "body",
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "h6",
    "b",
    "u",
    "i",
    "sub",
    "sup",
    "center",
    "strike",
    "font",
    "p",
    "style",
    "pre",
    "a",
    "img",
    "table",
    "tr",
    "th",
    "td",
    "form",
    "input",
    "div",
    };

 

KeyPress event : Get the pressed character.If it is "<" then set EnteredString="", Is_LessThanKeyPressed value to true and Is_SpaceBarKeyPressed value to false.
If pressed character is ">" then first check Is_TagClosedKeyPressed value is false or not, if it is false then set Is_GreaterThanKeyPressed value to true & Is_SpaceBarKeyPressed value to false and insert the closing tag at 
current SelectionStart position in RichTextBox by matching EnteredString with each element in tagslist.
Once tag is inserted then set EnteredString="".
If pressed key is other character then first check if it is letter or digit,if it is then concat that character with 
EnteredString.
Here's the code

private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    String ch = e.KeyChar.ToString();


    this.ProcessAutoCompleteBrackets(ch);

    if (ch == "<")
    {
        Is_LessThanKeyPressed = true;
        Is_SpaceBarKeyPressed = false;
        EnteredString = "";
    }
    else if (ch == ">")
    {
        if (!Is_TagClosedKeyPressed)
        {
            Is_GreaterThanKeyPressed = true;
            Is_SpaceBarKeyPressed = false;

            int oldsel = richTextBox1.SelectionStart;

            for (int i = 0; i < tagslist.Length; i++)
            {
                if (EnteredString == tagslist[i])
                {
                    richTextBox1.Text = richTextBox1.Text.Insert(oldsel, "<!--" + tagslist[i] + "-->");
                    richTextBox1.SelectionStart = richTextBox1.SelectionStart + oldsel;
                    EnteredString = "";
                }
            }

            Is_LessThanKeyPressed = false;
        }
        else
        {
            Is_TagClosedKeyPressed = false;
        }
    }

    else
    {
        if (Is_LessThanKeyPressed)
        {
            for (char a = 'a'; a <= 'z'; a++)
            {
                if (a.ToString() == ch)
                {
                    EnteredString += ch;
                }
                else if (a.ToString().ToUpper() == ch)
                {
                    EnteredString += ch;
                }
            }
            for (int a = 0; a <= 9; a++)
            {
                if (a.ToString() == ch)
                {
                    EnteredString += ch;
                }
            }
        }
    }


    // if user itself closes the tag
    if (Is_LessThanKeyPressed)
    {
        if (ch == "/")
        {
            Is_TagClosedKeyPressed = true;
            Is_SpaceBarKeyPressed = true;
            EnteredString = "";
        }
    }
}

 

KeyDown event : If key is Space then set the value of EnteredString to the same value of exists in tagslist.
If key is Up,Down,Left,Right then first check Is_AutoCompleteCharacterPressed is false,if it is then set 
EnteredString="" & Is_AutoCompleteCharacterPressed = false & Is_SpaceBarKeyPressed=false.
If key is Back then get the character from current position.if that character is not equal to ">" then remove that character from RichTextBox,if that character is "<" then set EnteredString="".

private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Space:
            Is_SpaceBarKeyPressed = true;

            if (Is_GreaterThanKeyPressed)
            {
                Is_GreaterThanKeyPressed = false;
            }
            Is_LessThanKeyPressed = false;

            for (int i = 0; i < tagslist.Length; i++)
            {
                if(EnteredString==tagslist[i])
                {
                    EnteredString = tagslist[i];
                }
            }
            break;

        case Keys.Up:
            if (Is_AutoCompleteCharacterPressed == false)
            {
                EnteredString = "";
                Is_AutoCompleteCharacterPressed = false;
            }
            Is_SpaceBarKeyPressed = false;
            break;

        case Keys.Down:
            if (Is_AutoCompleteCharacterPressed == false)
            {
                EnteredString = "";
                Is_AutoCompleteCharacterPressed = false;
            }
            Is_SpaceBarKeyPressed = false;
            break;

        case Keys.Left:
            if (Is_AutoCompleteCharacterPressed == false)
            {
                EnteredString = "";
                Is_AutoCompleteCharacterPressed = false;
            }
            Is_SpaceBarKeyPressed = false;
            break;

        case Keys.Right:
            if (Is_AutoCompleteCharacterPressed == false)
            {
                EnteredString = "";
                Is_AutoCompleteCharacterPressed = false;
            }
            Is_SpaceBarKeyPressed = false;
            break;

        case Keys.Enter: EnteredString = "";
            Is_SpaceBarKeyPressed = false;
            break;

        case Keys.Back:
            int sel = richTextBox1.SelectionStart;
            Point pt = richTextBox1.GetPositionFromCharIndex(sel);
            char ch = richTextBox1.GetCharFromPosition(pt);
            if (EnteredString.Length > 0)
            {
                if (ch != '>')
                {
                    EnteredString = EnteredString.Remove(EnteredString.Length - 1);
                    Is_LessThanKeyPressed = true;
                }
            }
            if (ch == '<')
            {
                EnteredString = "";
            }
            break;
    }
}

 

With AutoCompletion Feature

We will also create AutoComplete HTML tags with AutoCompletion(Code Completion) feature.
Dont know how to create AutoCompletion in C#,

         Creating Auto Completion/Code Completion in C#

Coding is same as defined in above article link,only just adding AutoComplete HTML tags feature and modifying contents.
Download the source code to view automatic html tags completion with autocompletion feature.
With autocompletion feature you can direcly select tags from the popped up list and can complete them by just pressing ">" key on it.
I have created ACHTMLTags.cs(AutoCompleteHTMLTags) class in source code.   

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