3

How I can convet viewstate to bool array

private bool[] clientCollapse
{
    get { return Convert.ToBoolean(ViewState["Collapse"]); }
    set { ViewState["Collapse"] = value; }
}

Any ideas???

6 Answers 6

3
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

Sign up to request clarification or add additional context in comments.

Comments

1

You can do this:

private bool[] clientCollapse
{
    get { return (bool[])ViewState["Collapse"] ?? new bool[0]; }
    set { ViewState["Collapse"] = value; }
}

Comments

1
private bool [] clientCollapse
{
    get { return (ViewState["Collapse"] as bool[]); }
    set { ViewState["Collapse"]; }
}

Comments

1

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;
         }

    }

Comments

1

try changing your getter to:

get { return ViewState["Collapse"] as bool[]; }

this will return null if it's not set.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.