记住,每次你做任何回发,即使只是为了处理一个事件,整个页面的生命周期都会运行。为了帮助理解这一点,你可以把你的代码想象成一个大函数,更像这样:
public partial class test : System.Web.UI.Page
{
// Page_Load runs for EVERYTHING
protected void Page_Load(object sender, EventArgs e)
{
// -- Constructor Area
StringBuilder sb = new StringBuilder();
// -- Page Init Area
// -- ViewSate is loaded
// -- Page Load Area
if (!IsPostBack)
{
sb.Append("one");
lbl.Text = sb.ToString();
}
// -- Validation controls are checked
// -- If valid, start handling events
// Handle your click event
if (cmdSb_Clicked)
{
sb.Append("two");
lbl.Text = sb.ToString();
}
// -- DataBinding Area
// -- Save ViewState
// -- Render Page: the class is turned into html that is sent to the browser
// -- Unload -- Page is disposed
}
}
当然,这不是实际发生的事情,但开始这样想,你就走在了正确的轨道上。在这种情况下,请注意您的 click 事件永远不会与您的!IsPostBack
代码同时运行,但您每次都使用新的 StringBuilder。
在此处查看有关页面生命周期的更多信息:http:
//msdn.microsoft.com/en-us/library/ms178472.aspx