Reputation: 1591
I'm working on my first C# application which will add a button to the MS Word ribbon that will insert a new table in the document. The content of the table needs to be populated using a value from the previous table in the document (if it exists). I'm able to insert the table but having trouble figuring out the best way to find the previous table. I create the new table and then get the total number of tables with this:
Word.Range rng = Application.Selection.Range;
rng.Font.Name = "Times New Roman";
rng.Font.Size = 10;
rng.InsertParagraphAfter();
rng.SetRange(rng.End, rng.End);
// Add the table.
Word.Table tbl = rng.Tables.Add(rng, 13, 2, ref missing, ref missing);
var number_of_tables = this.Application.Documents[1].Tables.Count;
However, where I am stuck is trying to figure out the index of the newly inserted table so I can do something like this:
var new_table_index = tbl...some code here...
if (new_table_index > 1)
{
previous_table = this.Application.Documents[1].Tables[new_table_index - 1];
}
How can I find the index of the table I just inserted? Thanks!
Upvotes: 2
Views: 341
Reputation: 25663
The usual way to do this is to count the number of tables from the start of the document to the table in question. In this case, to the range of the newly added table, then subtract one to get the previous table.
// Add the table.
Word.Table tbl = rng.Tables.Add(rng, 13, 2, ref missing, ref missing);
//Define a range from the start of doc to new table
Word.Range rngDocToTable = tbl.Range;
rng.Start = doc.Content.Start;
int nrTablesInRange = rng.Tables.Count;
//Get index of previous table
int indexPrevTable = nrTablesInRange - 1;
Word.Table previousTable = null;
if (indexPrevTable > 0)
{
previousTable = doc.Tables[indexPrevTable];
}
else
{
System.Windows.Forms.MessageBox.Show("No previous tables");
}
Upvotes: 1