Search code examples
c#.netwinformsrichtextboxhtml-editor

Edit HTML in text edit field in C#


I have a text string with basic HTML tags like <b> <i> <ul> <ol> tags.

Now I want to display it parsed in a editable text box and allow user to edit in a WYSIWYG way. How can I do it in C#?

Right now I have a RichTextBox but it uses RTF tags under the hood not HTML, so instead of formated text I see html code.


Solution

  • The easiest solution is using a WebBrowser control, showing editable div:

    private void Form1_Load(object sender, EventArgs e)
    {
        webBrowser1.DocumentText = @"
        <div contenteditable=""true"">
            This is a sample:
            <ul>
                <li>test</li>
                <li><b>test</b></li>
                <li><a href=""https://stackoverflow.com"">stackoverflow</a></li>
            </ul>
        </ div >";
    }
    

    You can also have some toolbar buttons for setting text bold, italic, or insert <ul> or ol and other commands. For example, the following command, makes the selection bold:

    webBrowser1.Document.ExecCommand("Bold", false, null);
    

    Or the following command inserts ordered list:

    webBrowser1.Document.ExecCommand("InsertOrderedList", false, null);
    

    You may also want to take a look at following post:

    Windows Forms HTML Editor

    Windows Forms HTML Editor