views:

93

answers:

0

In our VSTO Word 2010 Addin, we are trying to insert a RichTextControl after a given other ContentControl. We have tried this:

    public ContentControl AddContentControl(WdContentControlType type, int position)
    {
        Paragraph paragraphBefore = null;
        if (position == 0)
        {
            if (WordDocument.Paragraphs.Count == 0)
            {
                WordDocument.Paragraphs.Add();
            }
            paragraphBefore = WordDocument.Paragraphs.First;
        }
        else
        {
            paragraphBefore = Controls.ElementAt(position - 1).Range.Paragraphs.Last;
        }

        object start = paragraphBefore.Range.End;
        object end = paragraphBefore.Range.End + 1;

        paragraphBefore.Range.InsertParagraphAfter();

        Range rangeToUse = WordDocument.Range(ref start, ref end);

        ContentControl newControl = _ContentControl = _WordDocument.ContentControls.Add(type, rangeToInsert);

        Controls.Insert(position, newControl);

        OnNewContentControl(newControl, position);

        return newControl.ContentControl;
    }

which works fine, unless the control that is before the one we want to insert has an empty paragraph at the end. If that is the case, the new ContentControl is inserted within the last control.

How can we avoid this?