日期:2014-05-18  浏览次数:21076 次

用户控件上定的的变量无法更新?急~~~~~
用户控件
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="cOperator.ascx.cs" Inherits="cOperator" %>
&nbsp;<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button1" />
<asp:Label ID="Label1" runat="server" Text="0"></asp:Label>&nbsp;
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
--------------------------------------------------------------------
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class cOperator : System.Web.UI.UserControl
{
  private int __i=0;
  protected void Page_Load(object sender, EventArgs e)
  {

  }
  protected void Button1_Click(object sender, EventArgs e)
  {
  this.__i++;
  Label2.Text = __i.ToString();
  Label1.Text = (int.Parse(Label1.Text)+1).ToString();
  }
}

调用用户控件
--------------------------------------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="kf_jh.aspx.cs" Inherits="kf_jh" %>

<%@ Register Src="cOperator.ascx" TagName="cOperator" TagPrefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>无标题页</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
  <uc1:cOperator ID="COperator1" runat="server" />
   
  </div>
  </form>
</body>
</html>

--------------------------------------------------------------------
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class kf_jh : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {

  }
}
--------------------------------------------------------------------
问题:
当点Button1时,Label1显示1,再点变2,以此类推,但Label2的值却始终为1,为何???


------解决方案--------------------
viewstate:
获取状态信息的字典,这些信息使您可以在同一页的多个请求间保存和还原服务器控件的视图状态。
服务器控件的视图状态为其所有属性值的累计。为了在 HTTP 请求间保留这些值,ASP.NET 服务器控件使用该属性(它是 StateBag 类的实例)来存储属性值。在处理后续请求时,该值随即作为变量传递给 HTML 隐藏输入元素
下面的示例演示如何实现从其控件的 ViewState 属性存储和检索值的 Text 属性。

C#:
private const int defaultFontSize = 3;
// Add property values to view state with set;
// retrieve them from view state with get.
public String Text
{
get 

object o = ViewState["text"]; 
return (o == null)? String.Empty : (string)o;
}

set
{
ViewState["Text"] = value;
}
}