-1

I have a user control on an aspx page that contains filter fields and return a WhereClause. The user conrol will raise an event called FilterApplied when Search is clicked.

On my main form, I add the control with:

<uc1:Filter runat="server" ID="Filter" />
<br />

In my code behind I have:

   protected void Page_Load(object sender, EventArgs e)
    {
        //Register event when filter is changed.
        this.Filter.FilterApplied += new EventHandler(this.FilterApplied);

        if (Page.IsPostBack)
        { //Do some things that take long 
        }
     }

    protected void FilterApplied(object sender, EventArgs e)
    {
        //Reload the page to refresh the graphs.
        Page_Load(sender, e);
    }

Problem is: When I click Search on my user control, the Form_Load runs twice. Once because it is reloaded and then another time because I call it from FilterApplied. If I don't call it from FilterApplied, then the whereclause is still empty.

How can I ensure the Page_Load only run once when Search is clicked?

4

1 回答 1

1

Your problem lays in multiple registering for FilterApplied event. Each time you call the Page_Load method, you subscribe to this event again. Here is a really simple example of what you are doing, written in WinForms with one button on the form, just to point out your problem:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private int numClicks = 0;

    private void Form1_Load(object sender, EventArgs e)
    {
        button1.Click += button1_Click;
        this.Text = numClicks.ToString();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        numClicks++;
        //try uncommenting and commenting next line of code, and observe the difference:
        //button1.Click -= button1_Click;
        Form1_Load(sender, e);
    }

}
于 2013-05-29T11:36:55.737 回答