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

Asp.net自定义控件开发任我行(4)-ViewState保存控件状态

2013-09-16 20:42 337 查看

摘要

  上一篇我们实现了下拉框的效果,此章的目的主要是保存控件属性状态

内容

  我们先来看一个例子,后台代码不变,我们只改UI页面的代码,先在页面上拖放两个控件,一个是我们现在要开发的这个控件,另一个是按钮Button

<body>
<form id="form1" runat="server">
<XYB:TextEdit ID="txt" DropDwonHeight="200" DropdwonWidth="200" runat="server"></XYB:TextEdit>
<asp:Button runat="server" ID="btn" Text="点击我" OnClick="btn_Click" />
</form>
</body>


我们在Page_Load里面给属性赋值,代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace XYB.UI
{
public partial class TextEditUI : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txt.DropDwonHeight = 100;
txt.DropdwonWidth = 100;
}

}

protected void btn_Click(object sender, EventArgs e)
{

}
}
}


我们运行浏览一下,第一次结果的确是100*100,但当我们点击一下按钮后,长和宽都还原成200了,也就是属性值没有被保存,现在我们只需要修改TextEdit.cs代码了,我们使用ViewState来保存控件属性状态值

using System;
using System.Text;
using System.Web.UI;
using System.ComponentModel;//包含组件开发所必须含有的(属性)Attribute;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

namespace XYB.Controls
{
public class TextEdit:TextBox
{
private int _dropDwonHeight;
private int _dropdwonWidth;

[Description("下拉框的高度"),//属性的描述
Category("下拉框")//所属目录
]
public int DropDwonHeight
{
//如果前台控件没有给DropDwonHeight赋值,那它的初始值是50
get { return ViewState["DropDwonHeight"] == null ? 150 : Convert.ToInt32(ViewState["DropDwonHeight"]); }
set { ViewState["DropDwonHeight"] = value; }
}

[Description("下拉框的宽度"),
Category("下拉框")
]
public int DropdwonWidth
{
get { return ViewState["DropdwonWidth"] == null ? 150 : Convert.ToInt32(ViewState["DropdwonWidth"]); }
set { ViewState["DropdwonWidth"] = value; }
}

protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
Panel pnlDropDown = new Panel();
pnlDropDown.ID = "pnlDropDownID";
pnlDropDown.Height = DropDwonHeight;
pnlDropDown.Width = DropdwonWidth;
pnlDropDown.Style["border"] = "1px solid #ccc";//设置边框样式
pnlDropDown.RenderControl(writer);//把下拉框呈现到网页上
}
}
}


重新生成控件运行,ok,当页面回发时,属性值依然不变。 

注意

  ViewState只在本页中可以有效,比如A页面中有一个ViewState["A"],那么在B页面中ViewState["A"]是为null的。

下集预告

  自定义控件内嵌资源,预知后事如何,请看下回分解。敬请关注我!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐