I am making a C# Web Application in .Net
I have overridden the Panel control to make a div clickable. It looks like this:
public class ProjectPanel : System.Web.UI.WebControls.Panel, System.Web.UI.IPostBackEventHandler
{
public ProjectPanel()
{
CssClass = "project";
this.Click += new EventHandler(ProjectPanel_Click);
}
public event EventHandler Click;
protected virtual void OnClick(EventArgs e)
{
if (Click != null)
{
Click(this, e);
}
}
public void RaisePostBackEvent(string eventArgument)
{
OnClick(new EventArgs());
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
this.Attributes.Add("onclick", "__doPostBack('" + this.ClientID + "', '');");
base.Render(writer);
}
public void ProjectPanel_Click(object sender, EventArgs e)
{
Label l = new Label();
l.Text = " HIYA";
this.Controls.Add(l);
}
}
Now, this works fine inside a Page. However, I also have a Web User Control which looks like:
<div class="team">
<asp:Panel runat="server" ID="TheCanvas" CssClass="projects" />
</div>
Now when I add the overriden Panel to the TheCanvas panel, the click event isnt registered anymore. The postback happens, but the ProjectPanel_Click doesnt fire. Any ideas? I’m adding the panel through code.
Instead of ClientID you should use UniqueID because when in another control client ID is prefixed with parend client ID, replace onclick attribute setting with this :
btw. you should be aware that if you don’t have on page another control that implements IPostBackDataHandler, __doPostback javascript would not be present and you will get javascript error:
You should implement IPostBackDataHandler and call Page.RegisterRequiresPostBack(this) inside your panel control, see details on this links:
http://aspalliance.com/1071_Smart_ListControl_in_ASPNET_1x20.4
http://www.timvasil.com/blog14/post/2007/10/30/Implementing-IPostBackDataHandler-once-and-for-all.aspx