Sunday, April 7, 2013

“Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate. “

The error is somewhat clear and somewhat unclear. It is clear in the sense Page.IsValid cannot be called before validation takes place.

Now we know that Page.IsPostback, IsCallback and IsCrossPagePostBack are all populated before Page_PreInit. Hence we guess that IsValid also may be populated before PreInit and thus try to use IsValid in either PreInit or Load.

And there is where we get this error.

This means IsValid is not populated before PreInit ? When is it populated then ?

Note that the Validation phase of page life cycle comes only after the load phase.
Hence to use IsValid without any worries, you have to wait till after page_load. 

However, you can avoid the above error by calling Page.Validate before checking IsValid.

I am not sure whether you will get the correct results till page_load, because the control values may change till that phase.

                 if ( Page.IsValid)

BTW, this is an exception of type System.Web.HttpException.

No comments:

Post a Comment