System.InvalidCastException in

时间:2012-12-26 08:23:05

标签: c# asp.net list viewstate

 System.InvalidCastException: [A]System.Collections.Generic.List`1[UploadImages] cannot be cast to [B]System.Collections.Generic.List`1[UploadImages].

  if (ViewState["CurrentList"] != null)
            {
        ObjUpload.AddRange((List<UploadImages>)ViewState["CurrentList"]); // Getting the above error  
            }

UploadImages ObjUp = new UploadImages();

    List<UploadImages> ObjUpload = new List<UploadImages>();

    ObjUp.AlternateText = TxtAlternatetext.Text;
    if (TxtFre.Text != "")
    {

        ObjUp.frequency = Convert.ToInt16(TxtFre.Text);
    }
    ObjUp.ImageURL = FileUpload1.PostedFile.FileName;

    ObjUp.URL = TxtUrlToNavigate.Text;
    ObjUp.ID = i;

    ObjUpload.Add(ObjUp);

我已经完成了我的班级[Serializable]

此代码有时有效但有时不起作用

1 个答案:

答案 0 :(得分:3)

使用as运算符确保:

List<UploadImages> uploadImages = ViewState["CurrentList"] as List<UploadImages>;

if(uploadImages != null)
{
    ObjUpload.AddRange(uploadImages); 
}