Reputation: 728
I have a custom control that will do some fancy stuff, once it knows the relationships of other controls. Here's how I've tried to wire this stuff up, I'm open to suggestions if you know a better way.
First I created some interfaces, then the control to manage the relationships.
public interface IRegisterSelf
{
string ParentId { get; set; }
string CustomControlId { get; set; }
void RegisterToControl(ICustomControl controller);
}
public interface ICustomControl
{
void Register(IRegisterSelf child, IRegisterSelf parent);
}
public class CustomControl : WebControl, ICustomControl
{
public List<KeyValuePair<IRegisterSelf, IRegisterSelf>> _relationShips
= new List<KeyValuePair<IRegisterSelf, IRegisterSelf>>();
public void Register(IRegisterSelf child, IRegisterSelf parent)
{
_relationShips.Add(new KeyValuePair<IRegisterSelf, IRegisterSelf>(parent, child));
}
}
After that, I created another custom control that adhere's to the IRegisterSelf interface:
public class CustomDDL : DropDownList, IRegisterSelf
{
public string ParentId { get; set; }
private ICustomControl _customControl;
public string CustomControlId
{
get
{
return ((Control)_customControl).ID;
}
set
{
_customControl = (ICustomControl)this.FindControl(value);
RegisterToControl(_customControl);
}
}
public void RegisterToControl(ICustomControl controller)
{
if (string.IsNullOrEmpty(ParentId))
controller.Register(this, null);
else
controller.Register(this, (IRegisterSelf)FindControl(ParentId));
}
}
Then the markup to define all these relationships:
<c:CustomControl ID="myControl" runat="server" />
<c:CustomDDL ID="box1" CustomControlId="myControl" runat="server">
<asp:ListItem Text="_value1" Value="Value 1" />
<asp:ListItem Text="_value2" Value="Value 2" />
<asp:ListItem Text="_value3" Value="Value 3" />
</c:CustomDDL>
<c:CustomDDL ID="box2" ParentId="box1" CustomControlId="myControl" runat="server">
<asp:ListItem Text="_value1" Value="Value 1" />
<asp:ListItem Text="_value2" Value="Value 2" />
<asp:ListItem Text="_value3" Value="Value 3" />
</c:CustomDDL>
The problem is, in the CustomControlId property of the CustomDDL, I can't register the controller because asp.net says it can't find it. FindControl always returns null. Why? I set the ID and I have the runat attribute set to server. I can even see it in the generated HTML. Any help would be appreciated.
Upvotes: 1
Views: 619