garma
garma

Reputation: 213

c# How to get an overrided Panel to work inside a User Control

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.

Upvotes: 1

Views: 800

Answers (2)

Gnani
Gnani

Reputation: 465

Your panel should be created with every postback. The postback happens but your panel does not exist on the sever side. Try adding panel through code on pageload function.

Upvotes: 1

Antonio Bakula
Antonio Bakula

Reputation: 20693

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 :

this.Attributes.Add("onclick", "__doPostBack('" + this.UniqueID + "', '');");

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:

__doPostBack is not defined

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

Upvotes: 0

Related Questions