多次运行页面加载

时间:2013-05-29 11:00:34

标签: c# events user-controls postback

我在aspx页面上有一个用户控件,其中包含过滤器字段并返回WhereClause。单击“搜索”时,用户控件将引发一个名为FilterApplied的事件。

在我的主表单上,我添加了控件:

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

在我的代码背后,我有:

   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);
    }

问题是: 当我单击“在我的用户控件上搜索”时,Form_Load会运行两次。一次,因为它被重新加载,然后另一次因为我从FilterApplied调用它。如果我没有从FilterApplied中调用它,那么whereclause仍然是空的。

如何确保Page_Load仅在单击“搜索”时运行一次?

1 个答案:

答案 0 :(得分:1)

您的问题在于多次注册FilterApplied事件。每次调用Page_Load方法时,都会再次订阅此事件。这是一个非常简单的例子,你在做什么,用WinForms编写,在表单上只有一个按钮,只是为了指出你的问题:

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);
    }

}
相关问题