日期:2014-05-17  浏览次数:21050 次

Page_Load中的Response.Write方法只执行一次,什么原因?
protected void Page_Load(object sender, EventArgs e)
  {
  if (!IsPostBack)
  {
  Response.Write("<script>alter('没有相关数据')</script>");
  SqlConnection myConn = GetConnection();
  string sqlStr = "select * from tb_News";
  SqlCommand myCmd = new SqlCommand(sqlStr, myConn);
  myCmd.CommandType = CommandType.Text;
  try
  {
  myConn.Open();
  SqlDataReader myDr = myCmd.ExecuteReader();
  this.Label1.Text = "序号 新闻内容<br>";
  //循环读取结果集
  while (myDr.Read())
  {
  //读取数据库中的信息并显示在界面中
  this.Label1.Text += myDr["NewsID"] + "&nbsp;&nbsp;&nbsp;&nbsp;" + myDr["NewsContent"] + "<br>";
  }
  //关闭DataReader
  myDr.Close();
  }
  catch (SqlException ex)
  {
  //异常处理
  Response.Write(ex.ToString());
  }
  finally
  {
  //关闭数据库的连接
  myConn.Close();
  }
  }

  }

Response.Write方法只执行了一次,再运行时就不执行了,但后面的语句执行,什么原因阿?

------解决方案--------------------
Page.IsPostBack是一个标志:当前请求是否第一次打开。
1)当通过IE的地址栏等方式打开一个URL时是第一次打开, 当通过页面的提交按钮或能引起提交的按钮以POST的方式提交的服务器时,页面就不再是第一次打开了。
2)IsPostBack只有在第一次打开的时候是false,其它时候都是true
3).Net判断一个Page是否第一次打开的方法:Request.Form.Count>0
4)每次页面Load的时候,根据需要把每次都要加载的代码放在IsPostBack中,只需要加载一次的代码放在if(!IsPostBack)中。
5)每次用户回传服务器任何信息的时候,都会引发isPostBack属性用来判断此用户是否曾经做过登陆或者其他事件 

也就是执行完后。就不在执行了。上面说的很清楚了