Dynamically adding event handlers to a dynamically created control
-
I've made a simple web user control that contains a placeholder and a label inside an HTML table, and I would like to make an event handler that allows me to click on any part of my control and redirect to another page. I just can't seem to get it to work. I think my problem is that I am trying to dynamically add my control to a page inside a loop (ie: there is more than one instance of my control on the page) this is my web control:
Public Event Click As EventHandler Private _thumbnailPath As String Private _name As String Private _id As Long Protected Overridable Sub OnClick(ByVal e As System.EventArgs) RaiseEvent Click(Me, e) End Sub Public Sub RaisePostBackEvent(ByVal eventArgument As String) Implements IPostBackEventHandler.Raisepostbackevent OnClick(EventArgs.Empty) End Sub Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim eqImage As New System.Web.UI.WebControls.Image eqImage.ImageUrl = "~/" & _thumbnailPath eqImage.Width = New System.Web.UI.WebControls.Unit(thumbnailWidth) lblEquipmentName.Text = _name phEquipmentImage.Controls.Add(eqImage) 'add image to my placeholder End Sub
then to add my control to the page I do it inside a loop:if not page.isPostBack then ' for each datarow in my dataset... For Each eqDT As DataRow In tmpEqDS.Tables(0).Rows ucEQ = Page.LoadControl("Controls\equipmentThumbnail.ascx") ' dynamically add my eventhandler to my control AddHandler ucEQ.Click, AddressOf ucEq_Click ' assign some values to my control ucEQ.EquipmentID = eqDT.Item("equipmentID") ucEQ.EquipmentName = eqDT.Item("equipmentName") ucEQ.EquipmentThumbnail = eqDT.Item("equipmentThumbPath") ' add my control to a placeholder phEquipment.Controls.Add(ucEQ) Next end if
and my event handler on that page is defined as:Private Sub ucEq_Click(ByVal sender As Object, ByVal e As System.EventArgs) 'Handles ucEq.Click Response.Redirect("http://www.google.com") End Sub
I am unsure of how to do this. My current code, when the user clicks on the control (any of them) it should redirect to www.google.com. this doesn't work at all. I have break points in there and it seems to assign the event to the eventhandler, but it just never gets fired. I'm unsure of where I have gone wrong so would really appreciate a bit of help on this /jason