Search code examples
c#outlookoffice-interop

c# outlook instantiate Items collection to add items in loop


I'm trying to create an application that moves items to a specific store/folder. I can either look on a specific folder and using folder.items collect the items and then use a foreach loop to move them one by one. This part works ok.

But I would like also to add the items using the drag-drop Windows forms functionality.

The problem I have is that I cannot create and instantiate a collection of Items (zero items). If I use null, the first time I try to add one MailItem it fails (System.NullReferenceException: 'Object reference not set to an instance of an object.' ). Also, I cannot leave the collection without a value because this will make the compiler to fail (Use of unassigned local variable). I've tried to work with List<Outlook.MailItem> but then I don't know how to convert this into an Outlook Items collection.

This is the event that loops through the selection in the active explorer:

private void dataGridViewRules_DragDrop(object sender, DragEventArgs e)
        {
            Outlook.Application application = Globals.ThisAddIn.Application;
            Outlook.Explorer explorer = application.ActiveExplorer();

            //instantiate
            Outlook.Items items = null;

            foreach (MailItem mailItem in explorer.Selection)
            {
                items.Add(mailItem);
            }

            //uses a reversed for loop and uses item.move to move each MailItem
            MoveMailItemsTest(items);
        }

Any ideas?


Solution

  • You cannot create a standalone Items collection - Items object can only exist in the context of the parent folder (MAPIFolder.Items). But I am not sure why you declare your items variable above as Items instead of List<MailItem>. Is it only because your existing MoveMailItemsTest() method takes Items as a parameter? You woudl have to redesign that.