ahmed abdelqader
ahmed abdelqader

Reputation: 3560

How to Add row in word document table by C#

While adding a new row into word document table I faced a next error:-

System.Runtime.InteropServices.COMException: 'The requested member of the collection does not exist.'

The complete code that I used:-

Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
object miss = System.Reflection.Missing.Value;
object path = string.Format(@"Doc_Path_here");
object readOnly = false;
Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
doc.Tables[0].Rows.Add();

I tried the solutions that existing here and here without any positive result.

any help is appreciated.

Update:-

The word document has one table, this is confirmed, and also the result nCount variable of next code is 1

int nCount = doc.Tables.Count;

Upvotes: 0

Views: 1142

Answers (1)

itsMasoud
itsMasoud

Reputation: 1375

As described here in MSDN:

The "requested member of the collection does not exist" error occurs when you try to access an object that does not exist.

You should check the existence of a member before trying to access it. You can use Count property of the collection to determine that the member exists.

And as @Cindy Meister mentioned in comments, Office collections are not Zero based. Try accessing it like this:

doc.Tables[1].Rows.Add();

Upvotes: 2

Related Questions