One of the easiest ways to insert a numbered list in MS Word is by starting to type such a list. MS Word recognizes that the user is creating a list and converts the text to a numbered list automatically. You might like this autonomy or not, but I had to recognize that this is a useful feature for the majority of MS Word users. Even if this quick Google search ("automatic numbered lists" turn off) returns about 25,300 results.

I recently saw this feature request in our support department and decided to share a short code snippet that illustrates how to implement such a feature. The philosophy behind TX Text Control is to keep it's API as flexible as possible. This implies that it is effortless to implement such features, based on the available methods and properties.

In MS Word, the paragraph is converted into a list after adding a {SPACE} or {TAB} character. I personally prefer that the conversion occurs after pressing {ENTER}, but this is more or less a matter of taste.

The following code uses the KeyPress event to check the text of the previous line. The LineCollection helps to get the line's text without selecting it. If the text starts with "1. " (or any other pattern), we simply need to convert the paragraph to a list and we are done.

// [C#]

private string _sMatchString = "1. ";

private void textControl1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar != 13)
        return;

    TXTextControl.Line linePreviousLine =
        textControl1.Lines.GetItem(textControl1.Selection.Start - 1);

    string sLineText = linePreviousLine.Text;

    if (sLineText.StartsWith(_sMatchString))
    {
        int iOriginalPosition = textControl1.Selection.Start;

        textControl1.Select(linePreviousLine.Start - 1, _sMatchString.Length);
        textControl1.Selection.Text = "";
        textControl1.Selection.ListFormat.Type =
            TXTextControl.ListType.Numbered;
        textControl1.Selection.Start = iOriginalPosition;
        textControl1.Selection.ListFormat.Type =
            TXTextControl.ListType.Numbered;
    }
}