简体   繁体   中英

Event handling for dynamically generated controls

I am working on a module where I am basically generating all the controls on the page dynamically using XSLT. They are being rendered and added to the mark up right. Here the problem is that I want to write event handling for this dynamically generated controls and I am not sure how to achieve that because in perfect development environment, we normally double click on our control on aspx page and .NET creates a related event for you in the back on the aspx.cs page.

Any ideas?

Dynamically-added controls generally do not survive postback.

No amount of double-clicking, or even typing the expected names of the controls with _selectedIndexChanged is going to get you what you want.

This is ASSUMING (please let us know if I'm right or wrong) that you are adding HTML controls, not ASP.NET controls dynamically.

If you want to execute client-side events, you can specify the name of the method to fire (or the code itself) by adding the appropriate attribute.

For example, if you want to fire myCheckBox_OnClick when the user clicks your dynamically generated checkbox, you can do the following:

myDynamicallyGeneratedControl.Attributes.Add("onclick", "myCheckBox_OnClick");

You could also generate the javascript code that is to be executed and add it to the page through the page's ClientScript.RegisterStartupScript method.

You'll need to create a method with the appropriate handler and wire it up to your dynamically created controls when you create them.

ie

protected void MyHandler(object sender, EventArgs e)
{
    //Do some stuff
}

when you create your controls

LinkButton lb = new LinkButton();
    lb.ID = "lbexample";
    lb.Click += MyHandler;
Page.Form.Controls.Add(lb);

But it's very important that on your postback, you rebuild these controls as they were or the event won't fire. You'll need to recreate the controls first so that the event can be raised, so any data that you'll need to create the controls will have to be available on the post back using whatever state mechanism you're comfortable with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM