C# convert viewstate to bool array
How I can convet viewstate to bool array
private bool[] clientCollapse
{
get { return Convert.ToBoolean(ViewState["Collapse"]); }
set { ViewState["Collapse"] = value; }
}
Any idea开发者_开发知识库s???
private bool[] clientCollapse
{
get { return (bool[])ViewState["Collapse"]; }
set { ViewState["Collapse"] = value; }
}
if will work if you set those values only using this propery, otherwise you can but there other type and cast will not work
BTW common naming convention for C# requires property names to start with capital: ClientCollapse
You can do this:
private bool[] clientCollapse
{
get { return (bool[])ViewState["Collapse"] ?? new bool[0]; }
set { ViewState["Collapse"] = value; }
}
private bool [] clientCollapse
{
get { return (ViewState["Collapse"] as bool[]); }
set { ViewState["Collapse"]; }
}
You may use extension methods so that you use it ViewState<byte[]>.GetTypedData(key)
:
public static class ViewStateExtensions
{
public static T GetTypedData<T>(this StateBag bag, string key)
{
return (T) bag[key];
}
public static void SetTypedData<T>(this StateBag bag, string key, T value)
{
bag[key] = value;
}
}
try changing your getter to:
get { return ViewState["Collapse"] as bool[]; }
this will return null if it's not set.
You should be using casts to do this:
private bool [] clientCollapse
{
get { return (bool[]) ViewState["Collapse"]); }
set { ViewState["Collapse"] = value; }
}
ASP.NET's serialization of view state will do the rest for you.
精彩评论