Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.NET Server Control Postback

I have a Control I want to create. Here's a simple example of what I was to accomplish.

I want the control to contain a button.

Button b = new Button();
b.Text = "Test";
b.Click += new EventHandler(b_Click);

this.Controls.Add(b);

Now, the control renders fine, the button shows up on the page. The heart of the problem I'm having is that the b_Click Event Handler is never triggered.

protected void b_Click(object sender, EventArgs e)
{
    throw new NotImplementedException();
}

Any help here would be much appreciated. I don't want to use a User Control here for purely selfish reasons and would like to totally encapsulate this in a single DLL.

Thanks In Advance.

EDIT**

namespace ClassLibrary1
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]
    public class WebCustomControl1 : WebControl
    {

        protected override void CreateChildControls()
        {
            Button b = new Button();
                    b.ID = "button";
            b.Text = "Click Me";
            b.Click += new EventHandler(b_Click);

            this.Controls.Add(b);

            base.CreateChildControls();
        }

        protected void b_Click(object sender, EventArgs e)
        {
            this.Controls.Add(new LiteralControl("<p>Click!</p>"));
        }

    }
}

So from the comments I've tried this. The simplest of exampes, still no go. Is there something I'm fundamentally missing?

like image 831
Aaron Avatar asked Feb 27 '26 17:02

Aaron


1 Answers

public class WebCustomControl1 : WebControl

needed to be

public class WebCustomControl1 : WebControl, INamingContainer

that's it. that's all that was needed to make this postback issue work.

like image 53
Aaron Avatar answered Mar 02 '26 06:03

Aaron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!