tags:

views:

100

answers:

3

I have been write code in Page_Load function like this

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        UserControl1.Button_Clicked += new EventHandler(UserControl1_Button_Clicked);
    }
}

But the same function will be added again when the page is directing to this page from the other page.

Is there any kind of method to prevent it happened?

I'm trying to use session to prevent it, but I would like to know is there any better method can do the same work. Thanks a lot!

+1  A: 

Hey Kirk

In C# ASP.NET, an event handler for a control must be added every time the page loads. That's how the framework works.

So, if you're going to declare custom event handlers for your controls, its cleaner to do so in the Page_Init event of the Page.

Lastly, as this needs to happen everytime, don't wrap the code in the "if(!IsPostBack)" condition.

andy
But if i dont wrap the code in the "if(!IsPostBack)" condition. When i click button and do post back, the button click method will be raised two times!
Kirk
try putting the code where you set the event handler just once in the Page_Init event of the Page, test it, and let me know if the button event fires twice. cheers
andy
+1  A: 

I would recommend setting autoeventwireup = false in your .aspx page, as well. Then, in your code behind page (.cs file), add the event for your button handler in the page_init.

I've seen where that will sometimes cause my events to be fired twice, if I leave that as true.
The (!isPostBack) condition shouldn't be needed for a button.

Dan
A: 

the stupid method is like this :

declare a variable Private a As Boolean = True

Protected Sub cmd_Entry_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmd_Entry.Click If a = IsPostBack Then saveData() clearData() a = False End If End Sub

that should work :D