C#方法的作用

时间:2013-10-22 17:28:08

标签: c# asp.net

 protected void Page_Load(object sender, EventArgs e)
 {       
    Panel1.Visible = True;
    Panel2.Visible = false;
    LoadQuestion(); // auto choose question from database and add into Panel1
    LoadQuestion1();  // auto choose question from database and add into Panel2                         
  }

当我启动程序时,我的表单会自动将问题加载到我的文本框和单选按钮列表中。我点击链接按钮2使我的Panel1 visible = false和Panel2 visible = true继续回答问题。但在我点击链接按钮2或1后,它将返回到Page_Load()方法并导致我的问题不断变化。

3 个答案:

答案 0 :(得分:2)

您应该检查它是否是回发。您只想在第一次加载时执行此操作。

protected void Page_Load(object sender, EventArgs e)
{       
   if(!IsPostBack) {
      Panel1.Visible = True;
      Panel2.Visible = false;
      LoadQuestion(); // auto choose question from database and add into Panel1
      LoadQuestion1();  // auto choose question from database and add into Panel2 
   }                      
}

Source

答案 1 :(得分:1)

尝试:

 protected void Page_Load(object sender, EventArgs e)
 {       
    if (!IsPostBack)
    {
        Panel1.Visible = True;
        Panel2.Visible = false;
        LoadQuestion(); // auto choose question from database and add into Panel1
        LoadQuestion1();  // auto choose question from database and add into Panel2   
    }
 }

答案 2 :(得分:1)

这是因为每次服务器处理对页面的请求时都会发生Load事件。

有两种请求:初始页面加载(当您转到URL时)和回发(当您单击按钮时)。你在Page_Load方法中所做的是有点初始化,所以它应该只在最初完成,而不是在回发期间。

protected void Page_Load(object sender, EventArgs e)
{       
    if( !IsPostBack )
    {
        // The code here is called only once - during the initial load of the page
    }

    // While the code here is called every time the server processes a request
}