扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:金属边缘 来源:天极开发 2007年11月6日
关键字: Windows
using System; using System.ComponentModel; using System.Security.Permissions; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebControlLibrary{ [ AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal), AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal), ToolboxData("<{0}:IndexButton runat=\"server\"> </{0}:IndexButton>") ] public class IndexButton : Button { // 定义私有变量 private int _indexInControlState; //利用控件状态实现属性 IndexInControlState [ Bindable(true), Category("Behavior"), DefaultValue(0), Description("该属性使用控件状态存储.") ] public int IndexInControlState { get { return _indexInControlState; } set { _indexInControlState = value; } } //利用视图状态实现属性 IndexInViewState [ Bindable(true), Category("Behavior"), DefaultValue(0), Description("该属性使用视图状态存储.") ] public int IndexInViewState { get { object obj = ViewState["IndexInViewState"]; return (obj == null) ? 0 : (int)obj; } set { ViewState["IndexInViewState"] = value; } } //重写OnInit方法,启用页面控件状态 protected override void OnInit(EventArgs e) { base.OnInit(e); Page.RegisterRequiresControlState(this); } //重写SaveControlState方法,保存控件状态数据 protected override object SaveControlState() { object obj = base.SaveControlState(); if (_indexInControlState != 0) { if (obj != null) { return new Pair(obj, _indexInControlState); } else { return (_indexInControlState); } } else { return obj; } } //重写LoadControlState方法,加载控件状态数据 protected override void LoadControlState(object state) { if (state != null) { Pair p = state as Pair; if (p != null) { base.LoadControlState(p.First); _indexInControlState = (int)p.Second; } else { if (state is int) { _indexInControlState = (int)state; } else { base.LoadControlState(state); } } } } } } |
<%@ Page Language="C#" EnableViewState="false" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@ Register Assembly="WebControlLibrary" Namespace="WebControlLibrary" TagPrefix="aspSample" %> <script runat="server"> void Page_Load(object sender, EventArgs e) { Label1.Text = (IndexButton1.IndexControlState++).ToString(); Label2.Text = (IndexButton1.IndexInViewState++).ToString(); } </script> <!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> 请单击该按钮: <aspSample:IndexButton Text="IndexButton" ID="IndexButton1" runat="server" /> <br /> <br /> Index属性值是: <asp:Label ID="Label1" runat="server" Text="Label"> </asp:Label> <br /> IndexInViewState属性值是: <asp:Label ID="Label2" runat="server" Text="Label"> </asp:Label> <br /> </div> </form> </body> </html> |
![]() 图1 |
婵″倹鐏夐幃銊╂姜鐢瓕鎻╅崚鍥╂畱閹厖绨$憴顤廡妫板棗鐓欓張鈧弬棰侀獓閸濅椒绗岄幎鈧張顖欎繆閹垽绱濋柇锝勭疄鐠併垽妲勯懛鎶姐€婄純鎴炲Η閺堫垶鍋栨禒璺虹殺閺勵垱鍋嶉惃鍕付娴f娊鈧柨绶炴稊瀣╃閵嗭拷