Irritating error trying to use CreateChildControls in a user control.

I was trying to programmatically add an ObjectDataSource to my CreateChildControls method:

ObjectDataSource ods = new ObjectDataSource();
ods.SelectMethod = “GetDataTable”;
ods.TypeName = “SPWebParts.LeadViewer.LeadViewerUserControl”;
ods.ID = “leadsDS”;
Controls.Add(ods);

This SHOULD work! However, everytime I was getting the error:

“The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.”

 No idea why.. However, the quick solution is just to instantiate the ODS declaratively instead of CreateChildControls.

 <asp:ObjectDataSource ID=”leadsDS” runat=”server” SelectMethod=”GetDataTable” TypeName=”SPWebParts.LeadViewer.LeadViewerUserControl”>
</asp:ObjectDataSource>

Problem solved!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s