简体   繁体   中英

Task export on MSProject with error on blank/empty tasks

I created an Addin in C# VSTO to export tasks from MSProject to a SQLServer. My code works fine until the tasks in MSProject have an empty/blank entry.

I have no idea for a workaround. It seems, that die foreach isn't working here.

    MsProject.Tasks tasks = Globals.ThisAddIn.Application.ActiveProject.Tasks;

    using (SqlConnection cnn = new SqlConnection(connectionString))
    {

    try
    {
        // Open the connection to the database.
        cnn.Open();

        foreach (Microsoft.Office.Interop.MSProject.Task t in tasks)
        {
                DateTime start = (DateTime)t.Start;
                DateTime finish = (DateTime)t.Finish;
                
                using (SqlCommand cmd = new SqlCommand(sql, cnn))
                {
                    // Create and set the parameters values 

                    cmd.Parameters.Add("@id", SqlDbType.Int).Value = t.ID;
                    cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = t.Name;
                    cmd.Parameters.Add("@start", SqlDbType.DateTime).Value = start;
                    cmd.Parameters.Add("@finish", SqlDbType.DateTime).Value = finish;
                    
                    int rowsAdded = cmd.ExecuteNonQuery();   
                }
            }
        
        MessageBox.Show("Data transfered" );


    }

            

In MSProject it looks like:

在此处输入图像描述

Does anyone have an idea how to loop over or include the blank/empty tasks?

Currently i only get NullPointerReference of the object as Error and the Third task won't be export to SQL Server.

This is a common problem. Whenever looping through tasks, check to see that the task object is not null before using it:

foreach (Microsoft.Office.Interop.MSProject.Task t in tasks)
{
    if (t != null)
    {
        DateTime start = (DateTime)t.Start;
        DateTime finish = (DateTime)t.Finish;
        // rest of code...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM