1
我有一個自定義控件,一旦知道其他控件的關係,就會做一些奇特的事情。以下是我試圖聯繫這些東西的方法,如果您知道更好的方法,我會接受建議。爲什麼不能asp.net找到我的自定義WebControl?
首先我創建了一些接口,然後是控制來管理關係。
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));
}
}
在那之後,我創建了一個堅持的對IRegisterSelf接口另一個自定義控制:
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));
}
}
然後標記來定義所有這些關係:
<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>
的問題是,在CustomDDL的CustomControlId屬性,我無法註冊控制器,因爲asp.net說它無法找到它。 FindControl總是返回null。爲什麼?我設置了ID,並將runat屬性設置爲server。我甚至可以在生成的HTML中看到它。任何幫助,將不勝感激。
請向我們展示您使用FindControl的位置以及您控制的父親。 – 2012-02-13 15:15:15