够显示在页面上的原因。
只有实现了IStateManger接口的集合才能够调用TrackViewState方法打开视图监控。如果没有实现此接口的对象,还有一种方法可以实现视图状态功能,把最初的代码修改成如下格式:
protected void Page_Load(object sender, EventArgs e)
{
ListBox lb = new ListBox();
this.form1.Controls.Add(lb);
if (!Page.IsPostBack)
{
lb.Items.Add("子项1");
}
}
在上面的代码中对之前不能够保存视图状态的代码,仅调换了一下代码顺序。把this.form1.Controls.Add(lb)这句放到了lb.Item.Add("子项1")之前。运行页面并单击"提交"按钮,就会发现item"子项1"也能够保存视图状态。仅作了代码调整即使 lb实现了视图状态保存,这是什么原因呢?这里的关键语句:
this.form1.Controls.Add(lb);
中的关键方法Add起了重要作用。Controls集合的Add方法最终调用的是Control控件基类中的方法AddedControl。直接看一下AddedControl的代码实现:
/// <summary>
/// 获得本书更多内容,请看:
/// http://blog.csdn.net/ChengKing/archive/2008/08/18/2792440.aspx
/// </summary>
protected internal virtual void AddedControl(Control control, int index)
{
if (control.OwnerControl != null)
{
throw new InvalidOperationException(SR.GetString("Substitution_
NotAllowed"));
}
if (control._parent != null)
{
control._parent.Controls.Remove(control);
}
control._parent = this;
control._page = this.Page;
control.flags.Clear(0x20000);
Control namingContainer = this.flags[0x80] ? this : this._namingContainer;
if (namingContainer != null)
{
control.UpdateNamingContainer(namingContainer);
if ((control._id == null) && !control.flags[0x40])
{
control.GenerateAutomaticID();
}
else if ((control._id != null) || ((control._occasionalFields != null)
&& (control._occasionalFields.Controls != null)))
{
namingContainer.DirtyNameTable();
}
}
if (this._controlState >= ControlState.ChildrenInitialized)
{
control.InitRecursive(namingContainer);
if (((control._controlState >= ControlState.Initialized) && (control.
RareFields != null)) && control.RareFields.RequiredControlState)
{
this.Page.RegisterRequiresControlState(control);
}
if (this._controlState >= ControlState.ViewStateLoaded)
{
object savedState = null;
if ((this._occasionalFields != null) && (this._occasionalFields.
ControlsViewState != null))
{
savedState = this._occasionalFields.ControlsViewState[index];
if (this.LoadViewStateByID)
{
control.EnsureID();
savedState =this._occasionalFields.ControlsViewState [control. ID];
this._occasi
|