开发者

How to set a view state in a master page?

I need to ch开发者_开发问答eck whether an event is fired from the master page or not. For that i kept a count in the viewstate . This is throwing exception on page load. I'm just calling the below line in a pageload

Int32 count = Int32.Parse(this.ViewState["Count"].ToString());

Please help.


This will throw an exception in a few cases.

  1. The key "Count" isn't in the view state yet. ViewState["Count"] will return null and the .ToString() call will throw a NullReferenceException.
  2. The value of "Count" can't be parsed into an int, throwing a FormatException.

Things to try:

  • You should check the ordering of your code to make sure that you are setting the value of count before attempting to read from it.

Your code can be improved as follows:

Int32 count;
string countStr = this.ViewState["Count"];

if(!string.IsNullOrEmpty(countStr )
{
    bool ok = Int32.TryParse(countStr, out count);

    if(ok)
    {
        // Do stuff with count
    }
}
  • You might consider using the Session rather than the ViewState to store custom data between pages.


<pagesenableSessionState="false"enableViewState="false"theme="Default" />


Make sure that ViewState["Count"] exist before performing operations to avoid exceptions.


Use this code to default the count value to 0:

Int32 count = Int32.Parse((this.ViewState["Count"] ?? "0").ToString());

This will stop you seeing an Exception if the "Count" key doesn't exist in the ViewState collection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜