ASP.NET回发问题

时间:2014-02-26 05:13:28

标签: c# asp.net

我正在学习ASP.NET,我不明白这里发生了什么。

文件背后的代码:

protected void Page_Load(object sender, EventArgs e)
{
    Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
    Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
}

protected void Button1_Click(object sender, EventArgs e)
{
    TextBox1.Text = "Some more text";
    TextBox1.ForColor = System.Drawing.Color.Blue;
}

基本上所有只有一个标签可以告诉你文本框的颜色和文字是什么。当您点击按钮时,它会将颜色更改为蓝色,并重新加载页面。

为什么当您第一次按下按钮并重新加载页面时,标签不会更新为正确的信息?您必须再次按下该按钮才能读取文本框为红色。

有人可以提供此行为的解释吗?以及如何更改Page_Load方法来解决此问题?

3 个答案:

答案 0 :(得分:2)

在控件事件之前正在处理Page_Load事件。请参阅http://msdn.microsoft.com/en-us/library/ms178472.aspx处的页面生命周期说明。要修复它,请修改代码,以便Page_Load和Button_Click处理程序调用相同的方法来设置标签值。如果方法不是POSTBACK,则只执行Page_Load。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
       SetUpLabel();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    TextBox1.Text = "Some more text";
    TextBox1.ForeColor = System.Drawing.Color.Blue;

    SetUpLabel();
}

private void SetUpLabel()
{
    Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
    Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
}

答案 1 :(得分:2)

您需要在Page_Load中编写代码,如下:

protected void Page_Load(object sender, EventArgs e)
{
  if(!IsPostBack) //This condition allows a code to execute once when your page is load first time.
   {
    Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
    Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
   }
}

protected void Button1_Click(object sender, EventArgs e)
{
    TextBox1.Text = "Some more text";
    TextBox1.ForColor = System.Drawing.Color.Blue;

    Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
    Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();

}

答案 2 :(得分:1)

尝试一下,只需尝试此代码,此代码总是工作,不需要额外的代码

bool IsClick=false;
protected void Page_Load(object sender, EventArgs e)
{    
    Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
    Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
    if(IsClick)
    {
    TextBox1.Text = "Some more text";
    TextBox1.ForeColor = System.Drawing.Color.Blue;
    }
}


protected void Button1_Click(object sender, EventArgs e)
{
  IsClick=true;
}

这是我的想法

相关问题