I have a custom control that is thrown onto a UserControl that is
thrown onto a WebForm. Basically, I've got a scenario where if my
UserControl sets an attribute on the custom control in the ascx,
EnsureChildControls gets called, creating the control before the
UserControl is even added to the webform. The problem with this is
that the UniqueID of the custom control will be false, since OnInit
has yet to be called on its parent, somehow screwing up the creation
of its UniqueID. This results in all events from that control
failing. Here's a little pseudocode to help explain:
MyCustomControl.cs
------------------
public string CustomProp1
{
set
{
EnsureChildControls();
// Set something here.
}
}
MyUserControl.ascx
------------------
<myTag:MyCustomControl id="myCustomID" CustomProp1="something"
runat="server" />
MyWebForm.cs
-------------
OnLoad(EventArgs e)
{
MyUserControl control = LoadControl("MyUserControl.ascx");
// Things aren't good at this point*
control.ID = "myUserID";
panelContent.Controls.Add(control);
}
At the indicated point *, MyCustomControl already has it's UniqueID
set and it is "myCustomID" instead of "myUserID_myCustomID", or
"_ctlX_myCustomID" if I never plan to explicitly set the UserControl
ID. If I take the Attribute setting of CustomProp1 out of the ascx
and move it to the code behind of MyUserControl, everything works
fine. I think the difference is that OnInit gets fired first on
MyUserControl if the property setting is done in the code behind, but
EnsureChildControls in MyCustomControl gets called first if the
property setting is in the ascx. This causes the UniqueID of
MyCustomControl to get set before it's parent's UniqueID, making it
bogus. That's my guess anyway. It's definitely bogus at the time
it's needed to tie up events.
Has anyone else encountered this situation? Is there a clean way to
fix it? I'm looking for a best practice or something. I really need
EnsureChildControls to be in all the property settings or things blow
up all over, but I also need to be able to load UserControls to be
placed in WebForms, and set properties inside of those UserControls in
the ascx files. These two relatively simple things seem to conflict
as far as timing due to properties being set.
Any help will be greatly appreciated.