您的位置:首页 > 编程语言 > C#

[C#自学第三天]C# state 状态管理

2011-11-26 17:39 218 查看
在ASP开发中一个比较重要的方法-保存中间结果; 通过该方法,可以在session级别,页面级别或者整个程序过程中把中间结果记录下来,从而实现对于程序执行过程中的结果进行记录; 以下记录具体的方法 (视图状态ViewState, 查询字符串, 会话状态Session和Cookie):

1) ViewState 视图状态

视图状态是在单个页面中保存信息的第一选择,控件之间也使用ViewStat回发保存属性值,注意ViewStat只能用来保存简单的数据类型和自定义对象,如果要保存像dataset这样大数据量的数据,就需要考虑用类似Session这类的方法了;

ViewState["Counter"]=1;
int counter;
//如果查找一个集合中不存在的值,则会得到NullReferenceException异常,为了避免该错误,必须加个判断条件
if (ViewState["Counter"]!=null)
counter = (int)ViewState["Counter"];
else
ViewState["Counter"] = counter;

下面例子将描述一个具体的做法,通过ViewState来实现控件中结果的保存:

protected void btnSave_Click(object sender, EventArgs e)
{
SaveAllText(Controls,true);
}
private void SaveAllText(ControlCollection controls, bool saveNested)
{
foreach (Control control in controls)
{
if (control is System.Web.UI.WebControls.TextBox)
{
//使用唯一的control ID保存text
ViewState[control.ID] = ((System.Web.UI.WebControls.TextBox)control).Text;
}
if ((control.Controls != null) && saveNested)
{
SaveAllText(control.Controls, true);
}
}
}
private void RestoreAllText(ControlCollection controls, bool saveNested)
{
foreach (Control control in controls)
{
if (control is System.Web.UI.WebControls.TextBox)
{
if (ViewState[control.ID] != null)
((System.Web.UI.WebControls.TextBox)control).Text = (string)ViewState[control.ID];
}
if ((control.Controls != null) && saveNested)
{
RestoreAllText(control.Controls,true);
}
}
}

protected void btnRestore_Click(object sender, EventArgs e)
{
RestoreAllText(Controls,true);
}





1) 输入值到ID,Name,Aging栏位; 2)点击Save; 3)清空textbox里面的值; 4) 点restore,值又回来了.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: