asp.net Web server control with child controls, event not firing
I have a simple web control (TaskList) that can have children (Task) which inherit from LinkButton, that can be added declaratively or programatically. This works ok, but I can't get the onclick event of a Task to be fired in my code behind. The code ..
[ToolboxData("<{0}:TaskList runat=\"server\"> </{0}:TaskList>")]
[ParseChildren(true)]
[PersistChildren(false)]
public class TaskList : System.Web.UI.Control
{
//[DefaultProperty("Text")]
publi开发者_运维知识库c TaskList()
{}
private List<Task> _taskList = new List<Task>();
private string _taskHeading = "";
public string Heading
{
get
{
return this._taskHeading;
}
set
{
this._taskHeading = value;
}
}
[NotifyParentProperty(true)]
[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public List<Task> Tasks
{
get
{
return this._taskList;
}
set
{
this._taskList = value;
}
}
protected override void CreateChildControls()
{
foreach (Task task in this._taskList)
this.Controls.Add(task);
base.CreateChildControls();
}
protected override void Render(HtmlTextWriter writer)
{
writer.Write("<h2>" + this._taskHeading + "</h2>");
writer.Write("<div class='tasks_container'>");
writer.Write("<div class='tasks_list'>");
writer.Write("<ul>");
foreach (Task task in this._taskList)
{
writer.Write("<li>");
task.RenderControl(writer);
writer.Write("</li>");
}
writer.Write("</ul>");
writer.Write("</div>");
writer.Write("</div>");
}
}
public class Task : LinkButton
{
private string _key = "";
public string Key
{
get
{
return this._key;
}
set
{
this._key = value;
}
}
}
Markup:
<rf:TaskList runat="server" ID="tskList" Heading="Tasks">
<Tasks>
<rf:Task Key="ba" ID="L1" Text="Helllo" OnClick="task1_Click" runat="server" />
</Tasks>
</rf:TaskList>
The Onclick event task1_Click never fires when clicked (although a postback occurs).
TaskList needed to implement INamingContainer to correctly route the events of each Task.
You could also inherit from CompositeControl, which implements INamingContainer for you, instead of inheriting from Control.
Have you thought about INamingContainer.
精彩评论