开发者

How can I store an array in a ViewState in asp.net?

开发者 https://www.devze.com 2023-02-09 02:02 出处:网络
protected void Button2_Click(object sender, EventArgs e) { int[] L = { 1, 2, 3, 4, 5 }; ViewState[\"I\"] = L.ToArray();
protected void Button2_Click(object sender, EventArgs e)
    {
        int[] L = { 1, 2, 3, 4, 5 };
        ViewState["I"] = L.ToArray();
    }
protected void Button1_Click(object sender, EventArgs e)
    {
        int[] I = { };
        if (ViewState["I"] != null)
            I = (int[])ViewState["I"];
        for (int i = 0; i < I.Length; i++)
            Response.Write(I[i].ToString());
    }

When I run the program, an error occurs:

Unable to cast object of type 'System.Collections.Generic.List`1[System.Int32]' to type '开发者_JAVA百科System.Int32[]'.

Why does this error occur?


The ToArray() method create a IEnumerable collection, i.e. a List. and that is not a int[].

I also suggest just removing the "ToArray()" extension method


Remove the .ToArray() call. L is already an array of int's (int[] is an array constructor). The reason your getting the error is because you are trying to cast it back to an array of int's when it's being stored as IList.

So to reiterate, just don't call .ToArray and you should be good!

0

精彩评论

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