Sekhat
Sekhat

Reputation: 4489

struggling with programmatically adding user controls

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

Upvotes: 0

Views: 455

Answers (2)

M4N
M4N

Reputation: 96596

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).

Upvotes: 3

Kieron
Kieron

Reputation: 27127

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).

Upvotes: 1

Related Questions