填充树视图

时间:2014-02-21 16:33:56

标签: c# winforms treeview

我正在尝试使用任务和子任务填充树视图,这些子任务充当该特定任务的子节点。

我收到一条错误,上面写着评论显示错误,我是否认为这一切都错了或者我错过了一些愚蠢的东西?

  

“类型'System.ArgumentOutOfRangeException'的未处理异常   发生在System.Windows.Forms.dll“

 private void updateTreeView()
        {   

            //Clear before entry
            treeActiveTasks.Nodes.Clear(); 

            treeActiveTasks.BeginUpdate();    

            int parentCount = 0;

            //Update tasks
            foreach (Task task in m_user.Tasks)
            {
                if (!task.IsComplete)
                {
                    treeActiveTasks.Nodes[parentCount].Nodes.Add(task.Title); //Error showing on this line

                    int i = 0;
                    foreach (Subtask subtask in task.Subtasks)
                    {
                        if (!subtask.IsComplete)
                        {
                            treeActiveTasks.Nodes[0].Nodes[0].Nodes.Add(subtask.Title);
                        }                     

                        i++;
                    }
                    parentCount++;
                }               
            }


            treeActiveTasks.EndUpdate();
        }

2 个答案:

答案 0 :(得分:1)

第一次评估treeActiveTasks.Nodes[parentCount]时,Nodes集合为空(您已明确将其清除了几行),因此当您传入索引0时(值parentCount),ArgumentOutOfRangeException

我想你想要这样的东西:

private void updateTreeView()
{   
    treeActiveTasks.BeginUpdate();    
    treeActiveTasks.Nodes.Clear(); 
    foreach (var task in m_user.Tasks)
    {
        if (!task.IsComplete)
        {
            var taskNode = treeActiveTasks.Nodes.Add(task.Title);
            foreach (var subtask in task.Subtasks)
                if (!subtask.IsComplete)
                    taskNode.Nodes.Add(subtask.Title);
        }               
    }
    treeActiveTasks.EndUpdate();
}

或者使用LINQ:

private void updateTreeView()
{   
    treeActiveTasks.BeginUpdate();    
    treeActiveTasks.Nodes.Clear();
    treeActiveTasks.Nodes.AddRange(
        (from task in m_user.Tasks
         where !task.IsComplete
         select new TreeNode(
             task.Title,
             (from subtask in task.Subtasks
              where !subtask.IsComplete
              select new TreeNode(subtask.Title)
             ).ToArray())
        ).ToArray());
    treeActiveTasks.EndUpdate();
}

答案 1 :(得分:0)

我解决了问题所在,我正在向我尚未创建的父项添加子节点,因此例外。代码如下:

//Clear before entry
    treeActiveTasks.Nodes.Clear(); 

    treeActiveTasks.BeginUpdate();




    int parentCount = 0;

    //Update tasks
    foreach (Task task in m_user.Tasks)
    {
        if (!task.IsComplete)
        {
            treeActiveTasks.Nodes.Add(task.Title); 


            foreach (Subtask subtask in task.Subtasks)
            {
                if (!subtask.IsComplete)
                {
                    treeActiveTasks.Nodes[parentCount].Nodes.Add(subtask.Title);
                }

            }
            parentCount++;
        }
    }


    treeActiveTasks.EndUpdate();