1
votes

I have a VSTO project where a click of a button on the ribbon, opens a new Word doc with a specific template, and opens it with a custom task pane. On that pane is a button, which when clicked, i want to add a row to a table which exists in the doc template.

Currently i'm just getting a 'command failed' exception at run time when the button on the task pane is clicked. Here is the whole class. As you can see i've tried two ways to do it, both fail:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using word = Microsoft.Office.Interop.Word;

namespace TestWordAddin2010
{
    public partial class NewDescDMtaskPane : UserControl
    {
        public NewDescDMtaskPane()
        {
            InitializeComponent();
        }

        private void addSpare_Click(object sender, EventArgs e)
        {
            Globals.ThisAddIn.Application.ActiveDocument.Tables[1].Rows.Add(Globals.ThisAddIn.Application.ActiveDocument.Tables[1].Rows[1]);  //this doesn't work

            //word.Table wordTable = Globals.ThisAddIn.Application.ActiveDocument.Tables[1];
            //wordTable.Rows.Add(wordTable.Rows[1]);  //neither does this work
        }
    }
}

Any help appreciated.

1
In what way does it not work? Do you get an error? Is the row added in the wrong place? Please provide more information.Cindy Meister
I get a 'Command Failed' exception in visual studio. No rows are added to any table.Can'tCodeWon'tCode
Ahh, my mistake. I had a hidden table at the very top with Content Controls in. When i changed it to 'Tables[2]' it added a row to the table i wanted. However, i had actually intended to use content controls in that table too. Does this mean i can't add rows to a table with a content control?? Obviously i can experiment, but you may know the answer?Can'tCodeWon'tCode
Could you please provide exact repro steps? And which version of Word? I can look at it tomorrow if I know the exact scenario... FWIW content controls shouldn't prevent adding a row.Cindy Meister

1 Answers

0
votes

Most likely your first table contains merged cells. Then you won't be able to access individual rows in the Rows collection.

As a workaround you could use the Selection object as follows:

ActiveDocument.Tables(1).Range.Select();
Application.Selection.Collapse();
Application.Selection.InsertRowsAbove();