热门搜索:Photoshop 平面设计 Linux Vista Windows ASP.NET qq word 病毒 XP Excel 标志设计 

ASP.NET2.0的控件状态和视图状态探讨

来源:ZNXF(读取中...) 2006-6-8 【字体: 】 切换为


  IndexButton控件源码

using System;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomerControls
{
 [
  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 indexValue;
  [
   Bindable(true),
   Category("Behavior"),
   DefaultValue(0),
   Description("The index stored in control state.")
  ]

 public int Index
 {
  get
  {
   return indexValue;
  }
  set
  {
   indexValue = value;
  }
 }

 [
  Bindable(true),
  Category("Behavior"),
  DefaultValue(0),
  Description("The index stored in view state.")
 ]

 public int IndexInViewState
 {
  get
  {
   object obj = ViewState["IndexInViewState"];
   return (obj == null) ? 0 : (int)obj;
  }
  set
  {
   ViewState["IndexInViewState"] = value;
  }
 }

 protected override void OnInit(EventArgs e)
 {
  base.OnInit(e);
  Page.RegisterRequiresControlState(this);
 }

 protected override object SaveControlState()
 {
  //调用基类的方法,从基类得到控件状态的基值
  //如果indexValue不等于并且基类的控件状态不为null
  //使用Pair作为便利的数据结构来高效保存(和在LoadControlState方法中还原)
  //由两部分组成的控件状态
  object obj = base.SaveControlState();
  if (indexValue != 0)
  {
   if (obj != null)
   {
    return new Pair(obj, indexValue);
   }
   else
   {
    return (indexValue);
   }
  }
  else
  {
   return obj;
  }
 }

 protected override void LoadControlState(object state)
 {
  if (state != null)
  {
   Pair p = state as Pair;
   if (p != null)
   {
    base.LoadControlState(p.First);
    indexValue = (int)p.Second;
   }
   else
   {
    if (state is int)
    {
     indexValue = (int)state;
    }
    else
    {
     base.LoadControlState(state);
    }
   }
  }
 }
}
}

  代码讨论

  IndexButton 控件的实现阐释了三个任务,必须执行这三个任务才能使控件参与控件状态:

上一页  [1] [2] [3] [4] 下一页

关注此文的读者还看过:
    用户评论
评论内容:不能超过100字,需审核,请自觉遵守互联网相关政策法规。
发表评论: 匿名发表 用户名: loading 位网友发表了评论 查看评论
(0/100)