public partial class UploadControl : System.Web.UI.UserControl
    {
        Dictionary<string, FileUpload> files = new Dictionary<string, FileUpload>(17);        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(files.Count);
        }        protected void btnInsert_Click(object sender, EventArgs e)
        {            string name = fUpload.FileName;
            long length = fUpload.FileContent.Length / 1024;
            string type = fUpload.PostedFile.ContentType;            if (name.Length > 30)
                name = name.Substring(0, 30) + "... , "+length.ToString()+" KB";
            else
                name=name+" , "+length.ToString()+" KB";            if (type.Contains("image"))
            {
                ListItem lItem=new ListItem(name,fUpload.PostedFile.FileName);
                lbxItems.Items.Add(lItem);                files.Add(name, fUpload);
                
            }
            else
            {
                Response.Write("调用错误提示框");            }
        }
我点击添加按钮之后,向files中添加了一项,可是等到页面刷新之后,files的项目总数变为0..不知道是什么原因..

解决方案 »

  1.   

    这是当然的...HTTP是无状态的,你一刷新就重新初始化了页面...用ViewState或Session保存files变量或者在Page_Load事件中根据IsPostBack属性值重建它...
      

  2.   


    public partial class UploadControl : System.Web.UI.UserControl
        {
            Dictionary<string, FileUpload> files = new Dictionary<string, FileUpload>(17);        protected void Page_Load(object sender, EventArgs e)
            {
                if (Session["fileDict"] != null)
                {
                    Dictionary<string, FileUpload> getFiles = (Dictionary<string, FileUpload>)Session["fileDict"];
                    foreach (KeyValuePair<string, FileUpload> file in getFiles)
                    {
                        Response.Write(file.Key);
                    }
                }
            }        protected void btnInsert_Click(object sender, EventArgs e)
            {            string name = fUpload.FileName;
                long length = fUpload.FileContent.Length / 1024;
                string type = fUpload.PostedFile.ContentType;            if (name.Length > 30)
                    name = name.Substring(0, 30) + "... , "+length.ToString()+" KB";
                else
                    name=name+" , "+length.ToString()+" KB";            if (type.Contains("image"))
                {
                    ListItem lItem=new ListItem(name,fUpload.PostedFile.FileName);
                    lbxItems.Items.Add(lItem);                if (Session["fileDict"] == null)
                    {
                        files.Add(name, fUpload);
                        Session.Add("fileDict", files);
                    }
                    else
                    {
                        Dictionary<string, FileUpload> getFiles = (Dictionary<string, FileUpload>)Session["fileDict"];
                        getFiles.Add(name, fUpload);
                    }
                    
                }