none
Interop.Word.Documents.Count and Content mismatch? RRS feed

  • Question

  • Hi,

            There is a problem which really bugs me for a long time.

            I am currently using Interop.Word in my application such that the users can start up word applications within it. The following code shows what I have done:

            App = new Word.Application();         // Create a new Word Application instance

            App.Visible = true;              // Making the Word window visible

            App.Documents.Add();        // This statement is called every time when user wants to create a new document

            On the other hand, I have placed the names of opened documents in a listbox such that users can open the document windows quickly.

           

            FileList.Items.Clear();         // Make sure that the list is empty at the beginning

            if (App.Documents.Count != 0)    // Do something to the listbox if and only if there are existing opened documents
            {
                    MessageBox.Show(App.Documents.Count); // Show the total number of opened documents in the Word application

                    foreach (Word.Document i in App.Documents)        // Iterate all items in the Documents collection
                    {
                        FileList.Items.Add(i.Name);        // Add the document name to the listbox
                    }
            }

            Now the problem comes when user closes the Word windows by hand. Suppose that a user creates 4 documents, namely Doc1, Doc2, Doc3 and Doc4 in sequence. If the Word window of Doc4 is closed by hand, the MessageBox above will certainly show "3", but the foreach statement will still add FOUR items to the FileList listbox, namely

            Doc3, Doc3, Doc2, Doc1. That means, the item Doc3 is duplicated.

            If the user closes the Word window for Doc3, the MessageBox will show "2", but the FileList listbox becomes more rediculous:

            Doc2, Doc1, Doc2, Doc1   <-  What does it mean?

            Things will become normal when Doc2 window is closed as well, which will leave Doc1 as the only item in the FileList listbox.

            So, have I missed something in my code? Should I handle something when the user closes the Word windows by hand?

            Thanks a lot!

    P.S. I have tried out the same thing with Interop.Excel.Workbooks. Everything is fine.

    • Edited by Tim Tong Thursday, January 10, 2013 2:05 AM
    • Moved by Sheldon _Xiao Thursday, January 10, 2013 5:23 AM (From:Windows Presentation Foundation (WPF))
    Thursday, January 10, 2013 1:57 AM

Answers

All replies