Dynamic load of user control, problem with child controls event fi

G

Guest

I have a web form containing a button that when selected adds a user control
to a place holder. The user control contains a button. The first time the
user control is added the contained button fires Click event first time it is
selected. The second (andd successive) times the user control is added the
button Click event does not fire the first time, only on the second and
successive times.

This problem is caused by the naming of the controls. The second time the
user control is added it appears that the naming container still know about
the old control deleted from the placeholder when it generates the name for
the new added control (which appears to thus get the wrong name). So how do
i force it to have the correct name?

The code below is a crude version of the full code that is causing me the
problem!

The web form code:

**************************
Private Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Button1.Click

Dim ctl As WebUserControl2 = LoadControl("WebUserControl2.ascx")

PlaceHolder1.Controls.Clear()
PlaceHolder1.Controls.Add(ctl)

Session("w2") = True

End Sub
***************

The user control is added on page init:

********************
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)

If Session("w2") Then
Dim ctl As WebUserControl2 = LoadControl("WebUserControl2.ascx")

PlaceHolder1.Controls.Clear()
PlaceHolder1.Controls.Add(ctl)

End If

MyBase.OnInit(e)

End Sub
***************************


The user control contains a button that when selected writes text to a
textbox:

********************************
Private Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Button1.Click

TextBox1.Text = "Button clicked"

End Sub
**********************************
 
K

Karl Seguin

Try using Denis Bauer's dynamic placeholder control (free):
http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx

It takes care of dynamic control recreation across postback, which means you
woudlnt' need to recreate the control yourslef on init and use sessions. I
think it'll solve your problem.

karl
--
MY ASP.Net tutorials
http://www.openmymind.net/ - New and Improved (yes, the popup is
annoying)
http://www.openmymind.net/faq.aspx - unofficial newsgroup FAQ (more to
come!)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top