Web User Control Event prob.

  • Thread starter Thread starter Big D
  • Start date Start date
B

Big D

I have a class that inherits from System.Web.Ui.Usercontrol... all is
basically is is a button which is created progammatically such as:

public abstract class BaseFrontEndEditor : System.Web.UI.UserControl
{
protected Button btnEdit = new Button();

private void Page_Load(object sender, System.EventArgs e)
{

if( ! this.IsPostBack )
{
btnEdit.Text="Edit";
btnEdit.ID = "btnEdit";
this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
}
}

The button is then added to the class's control collection.

I created another usercontrol that inherrits from this class, and placed it
on a page. This works, and when I view the aspx page the control is on, I
see the button. However, clicking the button never fires the event handler
("btnEdit_Click"). I have tried adding the event handler in the controls
"initializeComponent", as well as immediately after it is added (as seen
above). I have placed a simple Response.Write("hello") in the btnEdit_Click
function and nothing happens when the button is clicked. In fact, even the
button disappears. What's happening?

Thanks for any help!

-D
 
You need to add the button every time the control loads - not just the first
time. I am guess you are checking the IsPostBack property and only doing it
the first time.

Please remember that HTTP is a stateless protocol. The page and all tis
contents are recreated every time there is a request. So if you only add
the button if the request is not a postback - after the button is clicked,
it is not created. And since it doesn't exist, there is no event to fire for
it.
 
Thanks, however it's still not working. You were, of course, right about
the stateless nature, so it is no longer only being adding if not postback.
The button is now still there after postback, but it still does not fire the
event.

I've updated it a bit now, and it works as follows

onInit : The button is created and its handler is added. I am specifying a
unique id for the button, and the id is the same after postback.

onPreRender: The control is added to the page.

Clicking the button has no effect! Why is this?

-D
 
On prerender is too late to add it to the page. The event handler would
have already fired by this point. So the second time the page loads - the
point at which the event would have fired is gone, and then you are just
adding the button to the page before the HTML is sent to the client.

You need to add the button to the page in page_init or page_load
 
Back
Top