我的用户控件想实现这样的功能:
一个button和一个lable(数字),每点击button一次,lable的数字自动加1,而且页面在引用该控件的时候,lable的值要能直接引用。 protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.Label Label1;
private void Page_Load(object sender, System.EventArgs e)
{
if (!this.IsPostBack)
a=1;
this.Label1.Text=a.ToString();
} override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load); } private void Button1_Click(object sender, System.EventArgs e)
{
this.a++;
} public int a
{
get
{
return (int)ViewState["a"];
}
set
{
ViewState["a"]=value;
}
}现在遇到这样的问题,我点击button后,对于a的修改值不会马上返回到lable中,这样我就无法按我所需要的获得lable的值。虽然我可以在button1_Click中加入显示字段,解决显示上的问题。但是我仍无法在页面中获得lable的值。请问我应该如何设置呢?请大家帮帮忙!谢谢。
一个button和一个lable(数字),每点击button一次,lable的数字自动加1,而且页面在引用该控件的时候,lable的值要能直接引用。 protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.Label Label1;
private void Page_Load(object sender, System.EventArgs e)
{
if (!this.IsPostBack)
a=1;
this.Label1.Text=a.ToString();
} override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load); } private void Button1_Click(object sender, System.EventArgs e)
{
this.a++;
} public int a
{
get
{
return (int)ViewState["a"];
}
set
{
ViewState["a"]=value;
}
}现在遇到这样的问题,我点击button后,对于a的修改值不会马上返回到lable中,这样我就无法按我所需要的获得lable的值。虽然我可以在button1_Click中加入显示字段,解决显示上的问题。但是我仍无法在页面中获得lable的值。请问我应该如何设置呢?请大家帮帮忙!谢谢。
{
get
{
return (int)ViewState["a"];
}
set
{
ViewState["a"]=value;
this.Label1.Text=a.ToString();
}
}
但是这样只能解决这个在label上的显示问题。当我如果有一个页面要用到这个控件,如果要在page_load()取这个值的时候,每次点击button后,好像都是只能取在button1_click发生前的值。我要如何才能取得button_click执行完后的值。
所以你在page_load()中只能取得上一次的值要不你自己加1也行,但这不是好办法就是
我只知道原因,还没想到好方法
如果这个值在page_load()中要用到的话,可以把用到的部分写成方法
然后在button1_click中执行
private string temp; private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
temp=control1.lable1.text; }
override protected void OnInit(EventArgs e)
{ InitializeComponent();
base.OnInit(e);
} private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load); }
}
在点击button后,现在都是获得的temp值都是点击button前的值。而我希望的是获得button后的值。
页面中加载这个事件
在button1_click中触发这个事件
public delegate void OnButtonClick();
public class control1
{
event OnButtonClick onClickHandler;
private void Button1_Click(object sender, System.EventArgs e)
{
this.a++;
onClickHandler();
}}在页面中可以加载这个事件
事件中写
temp=control1.lable1.text;
就可以了
异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。行 99: onClickHandler();
写成pubilc event OnButtonClick onClickHandler;
把这个控件拖到页面上,应该在事件栏能看到onClickHandler这个事件