Convert Outlook data and display into a DataGridView

Hi,

From the code below I would like to work out how to convert the data (an Outlook Table) and display it into a DataGridView. Is there any easy way todo this. I set the DataSource = table but it does not work.

Any ideas. The code below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;
 
 
namespace EmailScan
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
 
    private void Form1_Load(object sender, EventArgs e)
    {
      Microsoft.Office.Interop.Outlook.Application app = null;
      Microsoft.Office.Interop.Outlook._NameSpace ns = null;
 
      app = new Microsoft.Office.Interop.Outlook.Application();
      ns = app.GetNamespace("MAPI");
      ns.Logon(null, null, false, false);
 
 
 
      // Obtain Inbox
      Outlook.Folder folder =
      ns.GetDefaultFolder(
      Outlook.OlDefaultFolders.olFolderInbox)
      as Outlook.Folder;
      // Create filter
      string filter = "";
      Outlook.Table table =
      folder.GetTable(filter,
      Outlook.OlTableContents.olUserItems);
      // Remove default columns
      table.Columns.RemoveAll();
      // Add using built-in name
      table.Columns.Add("EntryID");
      table.Columns.Add("Subject");
      table.Columns.Add("ReceivedTime");
      table.Columns.Add("SenderEmailAddress");
      table.Sort("ReceivedTime", Outlook.OlSortOrder.olDescending);
      // Add using namespace
      // Date received
      table.Columns.Add(
      "urn:schemas:httpmail:datereceived");
 
      this.dataGridView1.DataSource = table;
      // Does not work!!
 
    }
  }
}

Open in new window

LVL 1
whorsfallAsked:
Who is Participating?
 
Gautham JanardhanConnect With a Mentor Commented:
and to use it

OutLookInterface FObject;
 
 private void btnMail_Click(object sender, EventArgs e)
        {
            FObject.populateInbox();
            grdVwData.DataSource = FObject.Mails;
        }
 
        private void btnContacts_Click(object sender, EventArgs e)
        {
            FObject.PopulateContact();
            grdVwData.DataSource = FObject.Contact;
        }
 
        private void btnAppointments_Click(object sender, EventArgs e)
        {
            FObject.PopulateAppointments();
            grdVwData.DataSource = FObject.Appointment;
        }
 
        private void btnNotes_Click(object sender, EventArgs e)
        {
            FObject.PopulateNotes();
            grdVwData.DataSource = FObject.Notes;
        }
 
        private void btnTasks_Click(object sender, EventArgs e)
        {
            FObject.PopulateTasks();
            grdVwData.DataSource = FObject.Tasks;
        }

Open in new window

0
 
Gautham JanardhanCommented:

using System;
using System.Collections.Generic;
using System.Text;
using MOI = Microsoft.Office.Interop;
using System.Data;
 
namespace OutlookInterface
{
    #region ---Outlook Interace---
    class OutLookInterface
    {
        #region ---Constants---
        const string FAppointment = "Appointment";
        const string FContact = "Contact";
        const string FMail = "Inbox";
        const string FTasks = "Tasks";
        const string FNotes = "Note";
        #endregion
 
        #region ---User defined variable---
        private MOI.Outlook.Application FOutlook = null;
        private MOI.Outlook.NameSpace FNamespace = null;
        private MOI.Outlook.MAPIFolder FFolder = null;
        DataSet FSet;
        #endregion
 
        #region ---Costructor---
        public OutLookInterface()
        {
            FOutlook = new MOI.Outlook.ApplicationClass();
            FNamespace = FOutlook.GetNamespace("MAPI");
 
            CreateTable();
        }
        #endregion
 
        #region ---Public Properties---
        public DataTable this[string TableName]
        {
            get
            {
                return FSet.Tables[TableName];
            }
        }
        public DataTable Appointment
        {
            get
            {
                return this[FAppointment];
            }
        }
        public DataTable Contact
        {
            get
            {
                return this[FContact];
            }
        }
        public DataTable Mails
        {
            get
            {
                return this[FMail];
            }
        }
        public DataTable Tasks
        {
            get
            {
                return this[FTasks];
            }
        }
        public DataTable Notes
        {
            get
            {
                return this[FNotes];
            }
        }
        #endregion
 
        #region ---Private Methods---
        void CreateTable()
        {
            FSet = new DataSet();
 
            #region---Appointment Table---
            FSet.Tables.Add(FAppointment);
            Appointment.Columns.Add("Subject");
            Appointment.Columns.Add("Location");
            Appointment.Columns.Add("Start");
            Appointment.Columns.Add("End");
            Appointment.Columns.Add("AllDayEvent");
            Appointment.Columns.Add("Duration");
            Appointment.Columns.Add("Organizer");
            Appointment.Columns.Add("Importance");
            Appointment.Columns.Add("Sensitivity");
            Appointment.Columns.Add("Body");
            #endregion
 
            #region---Contach---
            FSet.Tables.Add(FContact);
            Contact.Columns.Add("FirstName");
            Contact.Columns.Add("LastName");
            Contact.Columns.Add("CompanyName");
            Contact.Columns.Add("Email");
            Contact.Columns.Add("HomePhone");
            Contact.Columns.Add("WorkPhone");
            #endregion
 
            #region---Mail---
            FSet.Tables.Add(FMail);
            Mails.Columns.Add("From");
            Mails.Columns.Add("To");
            Mails.Columns.Add("Cc");
            Mails.Columns.Add("Subject");
            Mails.Columns.Add("Received");
            Mails.Columns.Add("Message");
            #endregion
 
            #region---Tasks---
            FSet.Tables.Add(FTasks);
            Tasks.Columns.Add("Subject");
            Tasks.Columns.Add("Categories");
            Tasks.Columns.Add("CreationTime");
            Tasks.Columns.Add("LastModificationTime");
            Tasks.Columns.Add("Contents");
            #endregion
 
            #region---Notes---
            FSet.Tables.Add(FNotes);
            Notes.Columns.Add("Subject");
            Notes.Columns.Add("Categories");
            Notes.Columns.Add("CreationTime");
            Notes.Columns.Add("LastModificationTime");
            Notes.Columns.Add("Contents");
            #endregion
        }
 
        public int GetFolderCount(MOI.Outlook.OlDefaultFolders folder)
        {
            FFolder = FNamespace.GetDefaultFolder(folder);
            return FFolder.Items.Count;
        }
        public void PopulateAppointments()
        {
            MOI.Outlook.AppointmentItem FItem;
            try
            {
                FFolder = FNamespace.GetDefaultFolder(MOI.Outlook.OlDefaultFolders.olFolderCalendar);
                foreach (object FTemp in FFolder.Items)
                {
                    FItem = (MOI.Outlook.AppointmentItem)FTemp;
                    Appointment.Rows.Add(new object[] {
						FItem.Subject,
						FItem.Location,
						FItem.Start,
						FItem.End,
						FItem.AllDayEvent,
						FItem.Duration,
						FItem.Organizer,
						FItem.Importance,
						FItem.Sensitivity,
						FItem.Body
					});
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }
        public void PopulateContact()
        {
            MOI.Outlook.ContactItem FItem;
            try
            {
                FFolder = FNamespace.GetDefaultFolder(MOI.Outlook.OlDefaultFolders.olFolderContacts);
                foreach (object temp in FFolder.Items)
                {
                    FItem = (MOI.Outlook.ContactItem)temp;
                    Contact.Rows.Add(new object[] {
						FItem.FirstName,
						FItem.LastName,
						FItem.CompanyName,
						FItem.Email1Address,
						FItem.HomeTelephoneNumber,
						FItem.BusinessTelephoneNumber
					});
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }
        public void populateInbox()
        {
            MOI.Outlook.MailItem FItem;
            try
            {
                FFolder = FNamespace.GetDefaultFolder(MOI.Outlook.OlDefaultFolders.olFolderInbox);
                foreach (System.Object _FItem in FFolder.Items)
                {
                    FItem = (MOI.Outlook.MailItem)_FItem;
                    Mails.Rows.Add(new object[] {
						FItem.SenderEmailAddress,
						FItem.To,
						FItem.CC,
						FItem.Subject,
						FItem.ReceivedTime,
						FItem.Body
					});
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }
        public void PopulateNotes()
        {
            MOI.Outlook.NoteItem FItem;
 
            try
            {
                FFolder = FNamespace.GetDefaultFolder(MOI.Outlook.OlDefaultFolders.olFolderNotes);
                foreach (System.Object _FItem in FFolder.Items)
                {
                    FItem = (MOI.Outlook.NoteItem)_FItem;
                    Notes.Rows.Add(new object[] {
						FItem.Subject,
						FItem.Categories,
						FItem.CreationTime,
						FItem.LastModificationTime,
						FItem.Body
					});
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }
        public void PopulateTasks()
        {
            MOI.Outlook.TaskItem FItem;
 
            try
            {
                FFolder = FNamespace.GetDefaultFolder(MOI.Outlook.OlDefaultFolders.olFolderTasks);
                foreach (object Temp in FFolder.Items)
                {
                    FItem = (MOI.Outlook.TaskItem)Temp;
                    Tasks.Rows.Add(new object[] {
						FItem.Subject,
						FItem.StartDate,
						FItem.DueDate,
						FItem.Status,
						FItem.Body
					});
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }
        #endregion
    }
 
    #endregion
}

Open in new window

0
 
hhvdwattCommented:
When invoking method populateInbox() I still get the error below

Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Outlook.MailItem'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00063034-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
0
 
hhvdwattCommented:
problem solved, olFolderInbox can contain non mail items, so check the object type before casting.

 public void populateInbox()
            {
                MOI.Outlook.MailItem FItem;
                try
                {
                    //check that the item that you are trying to reference as a MailItem is actually a MailItem
                    FFolder = FNamespace.GetDefaultFolder(MOI.Outlook.OlDefaultFolders.olFolderInbox);
                    foreach (Object temp in FFolder.Items)
                    {
                        if (temp is MOI.Outlook.MailItem)
                        {
                        FItem = (MOI.Outlook.MailItem)temp;
                        Mails.Rows.Add(new object[] {
                                    FItem.SenderEmailAddress,
                                    FItem.To,
                                    FItem.CC,
                                    FItem.Subject,
                                    FItem.ReceivedTime,
                                    FItem.Body
                              });}
                    }
                }
                catch (System.Exception e)
                {
                    Debug.WriteLine("Error populateInbox");
                    throw e;
                }
            }
0
All Courses

From novice to tech pro — start learning today.