简体   繁体   中英

Add Event Handler to User Control from custom object

I have created a user control that will contain a table of LinkButtons (and other information). I create the table rows in another custom object and return a TableRowCollection with the link buttons in certain cells of these table rows.

In the code behind for the user control I created an event handler for the button click of these LinkButtons. I pass the user control into the method call to create the table rows (using "this") and then attempt to add the event handler to the "Click" of the LinkButton. For some reason, the event handler doesn't fire on a post back caused by this button. Any ideas as to what I could do to make this event fire?

Here is the code where I create the button and add the event handler:

LinkButton button = new LinkButton();
button.Text = movie.Title;
button.Click += new EventHandler(control.Link_Click);
button.CommandArgument = result.LocalID.ToString();
cell1.Controls.Add(button);

Where "control" is the user control passed in as a parameter and "Link_Click" is the event handler.

Thanks in Advance!

First off, if the event handler is already inside the user control, there is no need to pass a reference to it into its own method. You can simply access any property or method inside the event handler.

Events rely on the control ID's to wire-up to the correct control. If you are not creating your linkbuttons exactly the same way every time on the postback, and ensuring that they have the same ID as they did before, then your event handler won't fire, because the ASP.Net pipeline won't be able to find what it thinks it the correct button in the control tree.

Additionally, if you are re-binding your user control to its datasource on every postback, this can cause events for some controls to get lost, for the same reason detailed above.

Check to make sure that you're recreating your controls properly every time, and that you're not re-binding your user control every time.

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