bbusseuil
bbusseuil

Reputation: 261

Events between an ASPX and ASCX

i'm a beginner in .NET, and search since yesterday morning to resolve my problem without finding the solution.

Here is my problem :

I create dynamically some User Controls by this way, because I need to give parameters :

List<ANNOUNCEMENT> listAnnouncement = getAnnoucements();
foreach(ANNOUNCEMENT ann in listAnnouncement)
{
    if(ann.IS_CURRENT_ANNOUNCEMENT && currentAnnouncement == null)
    {
         currentAnnouncement = ann;
    }
    List<Object> listParams = new List<Object>();
    listParams.Add(ann);
    AnnouncementPresentation ap = (AnnouncementPresentation)(Controller.LoadControl(Page, "~/UserControls/AnnouncementPresentation.ascx", listParams.ToArray()));
    /* important for the end of the method */
    ap.modifyAnnouncementButtonClick += new EventHandler(modifyAnnouncementButtonClick);
    pnl_announcements.Controls.Add(ap);
}

In this ASCX, I have a button, and when user will click on it, I want to call a method contained in my ASPX, so I do this in the ASCX :

public event EventHandler modifyAnnouncementButtonClick;
protected void btn_modify_announcement_Click(object sender, EventArgs e)
{
    PageAdminAnnonces.currentAnnouncement = annonce;
    modifyAnnouncementButtonClick(sender, e);
}

And this in the ASPX :

protected void modifyAnnouncementButtonClick(object sender, EventArgs e)
{
     initListOfAnnouncement();
     lbl_errors.Text = currentAnnouncement.TITLE;
}

I think everything works, but there is the problem : It works once, and at the end of the method, I delete my ASCX as you can see, and create new ASCX. But they don't have the methods, and when I click again, nothing works, so the ASPX is reloaded. After reloading, it works again.

Do i do something wrong?

Upvotes: 3

Views: 1550

Answers (1)

Lukasz M
Lukasz M

Reputation: 5723

According to the information in the comments, I suppose that your solution does not work because you are recreating the controls in the Click event handling method, which is very late in the page's lifecycle and should not be used for adding controls.

As mentioned in the comments, I suggest you to create the controls in Page_Init or Page_Load and not recreate them in the button's Click handling method. You should also assign a unique ID to each of them. Then, in the Click handler, you can use FindControl method to acces the created controls. Alternatively you can just save the references to the controls upon creation, so you can access them later easily.

Useful links:

Upvotes: 1

Related Questions