views:

267

answers:

2

I have the same problem as in the question Programmatically added User Control does not create its child controls.

After reading the question and answer I changed my code which now looks like this:

foreach (ITask task in tasks)
{
    TaskListItem taskListItem = LoadControl(
        typeof(TaskListItem),
        new object[] {task}
    ) as TaskListItem;

    taskListItem.TaskCompleteChanged += taskListItem_TaskCompleteChanged;                        

    taskListItemHolder.Controls.Add(taskListItem);
}

However, I'm still getting a user control whose child controls haven't been instantiated.

Any idea what I'm doing wrong?

Thanks in advance

+1  A: 

Make sure you're adding the controls in the CreateChildControls method (you can override it), also, give the control an ID (which needs to be the same everytime you add it).

Kieron
+2  A: 

You probably want to use this instead:

foreach (ITask task in tasks)
{
  TaskListItem taskListItem = LoadControl("~/TaskListItem.ascx") as TaskListItem;

  taskListItem.Task = task;
  taskListItem.TaskCompleteChanged +=
      taskListItem_TaskCompleteChanged;                        

  taskListItemHolder.Controls.Add(taskListItem);
}

This is because TaskListItem is not the type of the real control, but the type of the control's code-behind class. Check this page in MSDN (at the bottom, in the community content).

M4N