Click here to Skip to main content
12,953,065 members (37,562 online)
Rate this:
Please Sign up or sign in to vote.
A user control I add dynamically has an image with onClick event.
When the user control is added up the onClick event occours only from the second click and on.
Here is the .cs file of the webform:
Public partial class Site_DynamicPage : System.Web.UI.Page
    private static Control uc;
    private static string lastControl = null;
    private void loadDynamically()
        if (lastControl != null)
            uc = Page.LoadControl("~/Site/Controls/" + lastControl + ".ascx");
    protected void Page_Load(object sender, EventArgs e)
    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
        lastControl = ListBox1.SelectedValue;

Here a control is selected from the ListBox and appears on the PlaceHolder,
again the Click event of the user control doesn't fire on the first cilck.
Any solutions for this? Thax.
Posted 15-Oct-12 5:19am
Aman.A 15-Oct-12 13:56pm
can you please post your control markup and hosting page markup?
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

See this:[^]

As it states:
Controls are typically added to the page during the page's initialization stage. For details about page stages, see ASP.NET Page Life Cycle Overview.

You adding this during PageLoad. Events are registered earlier.
So they are working after second time when controls were added to page and events registered.
Member 7966831 16-Oct-12 4:59am
If I got you right I should call the loadDynamically function before the Page_Load event. I tried to call the function on PreLoad InitComplete Init and got the same result. However when I tried PreInit it shouted an error of PlaceHolder1 is null.
n.podbielski 16-Oct-12 5:20am
Did you tried Page_Init? I doing things like this on Init and it's working fine.
Member 7966831 16-Oct-12 5:31am
Yea I tried that still not working, maybe another code scripts would help?
n.podbielski 16-Oct-12 7:39am
How are you attaching this event?
Member 7966831 16-Oct-12 8:28am
I just changed the Page_Load event name to Page_Init
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

I managed to fix that by redirect to another page which redirects just back on the selectedIndexChanged event. Thax anyways guys.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    Print Answers RSS
Top Experts
Last 24hrsThis month
OriginalGriff 6,389
CHill60 3,490
Maciej Los 3,103
Jochen Arndt 1,975
ppolymorphe 1,920

Advertise | Privacy | Mobile
Web02 | 2.8.170525.1 | Last Updated 20 Oct 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100