Asp.net TextBox的TextChanged事件使用介绍_实用技巧

分享到:

在博客园里有位兄弟问了我一个问题,动态创建的控件是如何加载视图状态,还提到ProcessPostData方法的调用。这里我就用TextBox的TextChanged事件来说说视图数据的加载以及事件的触发。

我们首先还是来看一个demo吧:

代码如下:

运行结果如图:

现在我们来修改文本框的值,然后点击按钮提交页面,看看有什么事情发生

TextBox的TextChanged事件这时候发生了,运行结果如图:

现在我们什么也不做,再次点击按钮提交,看看会有什么效果:

这是为什么了,TextBox的TextChanged事件这时候没有触发。

大家是否知道TextBox的TextChanged事件触发的条件了,那好我们今天就一起来看看该事件是如何触发的。

这里我们首先来看看TextBox的定义:

public class TextBox : WebControl, IPostBackDataHandler, IEditableTextControl, ITextControl

public interface IPostBackDataHandler
{
bool LoadPostData(string postDataKey, NameValueCollection postCollection);
void RaisePostDataChangedEvent();
}
public interface IEditableTextControl : ITextControl
{
event EventHandler TextChanged;
}
public interface ITextControl
{
string Text { get; set; }
}


这里我们最主要的是关注IPostBackDataHandler接口的实现,

protected virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
base.ValidateEvent(postDataKey);
string text = this.Text;
string str2 = postCollection[postDataKey];
if (!this.ReadOnly && !text.Equals(str2, StringComparison.Ordinal))
{
this.Text = str2;
return true;
}
return false;
}

protected virtual void RaisePostDataChangedEvent()
{
if (this.AutoPostBack && !this.Page.IsPostBackEventControlRegistered)
{
this.Page.AutoPostBackControl = this;
if (this.CausesValidation)
{
this.Page.Validate(this.ValidationGroup);
}
}
this.OnTextChanged(EventArgs.Empty);
}



这里的RaisePostDataChangedEvent方法比较好理解,主要就是调用TextChanged事件方法,而LoadPostData方法中是可以取到textBox当前值(旧值 string text = this.Text;)和post过来的新值( postCollection[postDataKey]),如果当前textbox不是只读,并且新旧值不等的话,则吧新值赋给textbox的text属性,返回true,否者返回false,这里我们能否猜测textbox的LoadPostData返回true,我们才调用RaisePostDataChangedEvent方法。

在前面的asp.net Page事件处理管道我们曾经提到两段比较特殊的代码,一段是处理IPostBackDataHandler一段是处理IPostBackEventHandler。
首先我们还是来先看看

this.OnInitComplete(EventArgs.Empty);

if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End InitComplete");
}
if (this.IsPostBack)
{
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin LoadState");
}
this.LoadAllState();
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End LoadState");
this.Trace.Write("aspx.page", "Begin ProcessPostData");
}
this.ProcessPostData(this._requestValueCollection, true);
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End ProcessPostData");
}
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin PreLoad");
}
this.OnPreLoad(EventArgs.Empty);



这一段吧,在InitComplete之后、PreLoad之前我们这里在处理IPostBackDataHandler接口,这里主要是一个LoadAllState和ProcessPostData方法。

首先我们需要知道这里的_requestValueCollection是一个什么东西,其实很简单,如果是post主要是this._request.Form(其中有些过滤处理,如过滤掉__VIEWSTATE",__EVENTTARGET),如果是get请求有QueryString集合则是this._request.QueryString就是this._request.QueryString。

LoadAllState的主要带代码如下:

View Code
?private void LoadAllState()
{
object obj2 = this.LoadPageStateFromPersistenceMedium();
IDictionary first = null;
Pair second = null;
Pair pair2 = obj2 as Pair;
if (obj2 != null)
{
first = pair2.First as IDictionary;
second = pair2.Second as Pair;
}
if (first != null)
{
this._controlsRequiringPostBack = (ArrayList) first["__ControlsRequirePostBackKey__"];
if (this._registeredControlsRequiringControlState != null)
{
foreach (Control control in (IEnumerable) this._registeredControlsRequiringControlState)
{
control.LoadControlStateInternal(first[control.UniqueID]);
}
}
}
if (second != null)
{
string s = (string) second.First;
int num = int.Parse(s, NumberFormatInfo.InvariantInfo);
this._fPageLayoutChanged = num != this.GetTypeHashCode();
if (!this._fPageLayoutChanged)
{
base.LoadViewStateRecursive(second.Second);
}
}
}
protected internal virtual object LoadPageStateFromPersistenceMedium()
{
PageStatePersister pageStatePersister = this.PageStatePersister;
try
{
pageStatePersister.Load();
}
catch (HttpException exception)
{
if (this._pageFlags[8])
{
return null;
}
exception.WebEventCode = 0xbba;
throw;
}
return new Pair(pageStatePersister.ControlState, pageStatePersister.ViewState);
}
internal void LoadChildViewStateByID(ArrayList childState)
{
int count = childState.Count;
for (int i = 0; i < count; i += 2)
{
string id = (string) childState[i];
object savedState = childState[i + 1];
Control control = this.FindControl(id);
if (control != null)
{
control.LoadViewStateRecursive(savedState);
}
else
{
this.EnsureOccasionalFields();
if (this._occasionalFields.ControlsViewState == null)
{
this._occasionalFields.ControlsViewState = new Hashtable();
}
this._occasionalFields.ControlsViewState[id] = savedState;
}
}
}


LoadAllState方法注意到是加载每个控件的ControlState和ViewState数据,数据来源是通过LoadPageStateFromPersistenceMedium方法获得的,数据类容就是上次response中各控件的ControlState数据和ViewState数据。

接下来我们该看看ProcessPostData方法,

private void ProcessPostData(NameValueCollection postData, bool fBeforeLoad)
{
if (this._changedPostDataConsumers == null)
{
this._changedPostDataConsumers = new ArrayList();
}
if (postData != null)
{
foreach (string str in postData)
{
if ((str != null) && !IsSystemPostField(str))
{
Control control = this.FindControl(str);
if (control == null)
{
if (fBeforeLoad)
{
if (this._leftoverPostData == null)
{
this._leftoverPostData = new NameValueCollection();
}
this._leftoverPostData.Add(str, null);
}
}
else
{
IPostBackDataHandler postBackDataHandler = control.PostBackDataHandler;
if (postBackDataHandler == null)
{
if (control.PostBackEventHandler != null)
{
this.RegisterRequiresRaiseEvent(control.PostBackEventHandler);
}
}
else
{
if (postBackDataHandler != null)
{
NameValueCollection postCollection = control.CalculateEffectiveValidateRequest() ? this._requestValueCollection : this._unvalidatedRequestValueCollection;
if (postBackDataHandler.LoadPostData(str, postCollection))
{
this._changedPostDataConsumers.Add(control);
}
}
if (this._controlsRequiringPostBack != null)
{
this._controlsRequiringPostBack.Remove(str);
}
}
}
}
}
}
ArrayList list = null;
if (this._controlsRequiringPostBack != null)
{
foreach (string str2 in this._controlsRequiringPostBack)
{
Control control2 = this.FindControl(str2);
if (control2 != null)
{
IPostBackDataHandler adapterInternal = control2.AdapterInternal as IPostBackDataHandler;
if (adapterInternal == null)
{
adapterInternal = control2 as IPostBackDataHandler;
}
if (adapterInternal == null)
{
throw new HttpException(SR.GetString("Postback_ctrl_not_found", new object[] { str2 }));
}
NameValueCollection values2 = control2.CalculateEffectiveValidateRequest() ? this._requestValueCollection : this._unvalidatedRequestValueCollection;
if (adapterInternal.LoadPostData(str2, values2))
{
this._changedPostDataConsumers.Add(control2);
}
}
else if (fBeforeLoad)
{
if (list == null)
{
list = new ArrayList();
}
list.Add(str2);
}
}
this._controlsRequiringPostBack = list;
}
}

首先根据创建来的参数NameValueCollection的key来查找我们的Control控件,一般情况下控件是可以找到的,但是在load中动 态创建的控件这里是找不到的。这个方法分为两部分,以  ArrayList list = null;这句代码分开,一部分如果中不到control控件处理比较简单,如果找到看看它是不是PostBackDataHandler类型,如果不是 并且它的PostBackEventHandler不为空,那么我们直接调用它 的 this.RegisterRequiresRaiseEvent(control.PostBackEventHandler)方法,如果是 PostBackEventHandler类型的控件我们直接调用它的LoadPostData方法,

if (postBackDataHandler.LoadPostData(str, postCollection))
{
this._changedPostDataConsumers.Add(control);
}

同时从_controlsRequiringPostBack集合中移除该控件

if (this._controlsRequiringPostBack != null)
{
this._controlsRequiringPostBack.Remove(str);
}

该方法的第二部分是遍历controlsRequiringPostBack中的集合,它的处理方式和上面一部分类似,只是没有找到控件的id则记录下来

else if (fBeforeLoad)
{
if (list == null)
{
list = new ArrayList();
}
list.Add(str2);
}

默认情况下_controlsRequiringPostBack是包含动态创建的控件。这里我们也说说这个集合吧,

controlsRequiringPostBack的设置是在LoadAllState方法中的这一句代码:

this._controlsRequiringPostBack = (ArrayList) first["__ControlsRequirePostBackKey__"];有LoadAllState(加载数据状态)就有SaveAllState(保存数据状态),在SaveAllState中有这么一句代码:

   dictionary.Add("__ControlsRequirePostBackKey__", this._registeredControlsThatRequirePostBack);

其中_registeredControlsThatRequirePostBack集合定义在RegisterRequiresPostBack方法中。

public void RegisterRequiresPostBack(Control control)
{
if (!(control is IPostBackDataHandler) && !(control.AdapterInternal is IPostBackDataHandler))
{
throw new HttpException(SR.GetString("Ctrl_not_data_handler"));
}
if (this._registeredControlsThatRequirePostBack == null)
{
this._registeredControlsThatRequirePostBack = new ArrayList();
}
this._registeredControlsThatRequirePostBack.Add(control.UniqueID);
}

总之在这里动态添加的控件是没办法加载数据的,但是其它默认的控件在这里都可以处理。

现在我们来看看控件是如何添加的,在Control类中有一个AddedControl方法是真正添加控件的处理:

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._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._occasionalFields.ControlsViewState.Remove(control.ID);
}
else
{
savedState = this._occasionalFields.ControlsViewState[index];
this._occasionalFields.ControlsViewState.Remove(index);
}
}
control.LoadViewStateRecursive(savedState);
if (this._controlState >= ControlState.Loaded)
{
control.LoadRecursive();
if (this._controlState >= ControlState.PreRendered)
{
control.PreRenderRecursiveInternal();
}
}
}
}
}

在这个方法中有调用 this.Page.RegisterRequiresControlState(control) 和  control.LoadViewStateRecursive(savedState)方法,一个负责ControlState一个负责 ViewState的数据加载,当我们这里第2次和3次post请求时,在load创建textboxt控件就会加载它已有的控件状态和视图状态。
现在我们再来看看ProcessRequestMain中处理IPostBackEventHandler的那段带代码:

this.LoadRecursive();
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End Load");
}
if (this.IsPostBack)
{
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin ProcessPostData Second Try");
}
this.ProcessPostData(this._leftoverPostData, false);
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End ProcessPostData Second Try");
this.Trace.Write("aspx.page", "Begin Raise ChangedEvents");
}
this.RaiseChangedEvents();
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End Raise ChangedEvents");
this.Trace.Write("aspx.page", "Begin Raise PostBackEvent");
}
this.RaisePostBackEvent(this._requestValueCollection);
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End Raise PostBackEvent");
}
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin LoadComplete");
}
this.OnLoadComplete(EventArgs.Empty);

首先我们来看看_leftoverPostData集合是什么,它是在先前一次调用ProcessPostData方法时没有找到控件的一个id集合。在这里就可以找到该控件,执行路线主要就是 ArrayList list = null这句后面部分,最终还是要调用

if (adapterInternal.LoadPostData(str2, values2))
{
this._changedPostDataConsumers.Add(control2);
}

这个方法,这里第二次调用ProcessPostData方法主要就就是处理动态创建控件的事件问题。

这里我们再来看看RaiseChangedEvents方法吧:

internal void RaiseChangedEvents()
{
if (this._changedPostDataConsumers != null)
{
for (int i = 0; i < this._changedPostDataConsumers.Count; i++)
{
Control control = (Control) this._changedPostDataConsumers[i];
if (control != null)
{
IPostBackDataHandler postBackDataHandler = control.PostBackDataHandler;
if (((control == null) || control.IsDescendentOf(this)) && ((control != null) && (control.PostBackDataHandler != null)))
{
postBackDataHandler.RaisePostDataChangedEvent();
}
}
}
}
}

我想到这里TextBox的TextChanged事件的执行你应该很清楚了吧。而RaisePostBackEvent方法就不说,看代码大家都会明白的,

private void RaisePostBackEvent(NameValueCollection postData)
{
if (this._registeredControlThatRequireRaiseEvent != null)
{
this.RaisePostBackEvent(this._registeredControlThatRequireRaiseEvent, null);
}
else
{
string str = postData["__EVENTTARGET"];
bool flag = !string.IsNullOrEmpty(str);
if (flag || (this.AutoPostBackControl != null))
{
Control control = null;
if (flag)
{
control = this.FindControl(str);
}
if ((control != null) && (control.PostBackEventHandler != null))
{
string eventArgument = postData["__EVENTARGUMENT"];
this.RaisePostBackEvent(control.PostBackEventHandler, eventArgument);
}
}
else
{
this.Validate();
}
}
}

到这里我们在回忆一下,一般控件的状态信息保存是通过SaveAllState方法,而加载状态信息是在InitComplete之后、PreLoad之前的LoadAllState方法,加载的数据就是上次请求SaveAllState方 法保存的数据,加载状态后调用ProcessPostData方法来处理post过来的数据,动态添加的控件在第二次及后面每次请求添加时都会加载状态数 据,说直接一点是动态添加的控件在添加的时候就加载它的状态数据。在 Load之后、 LoadComplete之前就是我们处理控件的事件调用问题,这里我们再次调用ProcessPostData用来处理动态创建的控件与post过来的 数据,之后分别调用RaiseChangedEvents、RaisePostBackEvent方法拉起处理 IPostBackDataHandler、IPostBackEventHandler中的事件调用。

昵    称:
验证码:

相关文档: