ASP.net with C# Keeping a List on postback

爷,独闯天下 提交于 2019-12-07 04:58:38

问题


My situation goes like this: I have these lists with data inserted into them when a user presses an ADD button, but I guess on postback the Lists are re-zeroed. How do you keep them preserved? I've been looking for the answer, but I guess I don't quite understand how to use the session, etc.

I'm very new to ASP.net and not much better with C# it would seem.

public partial class Main : System.Web.UI.Page
{


 List<string> code = new List<string>();


protected void Page_Load(object sender, EventArgs e)
{
    //bleh   

}

protected void cmdAdd_Click(object sender, EventArgs e)
{

    code.Add(lstCode.Text);
}

回答1:


Just use this property to store information:

public List<string> Code
{
    get
    {
        if(HttpContext.Current.Session["Code"] == null)
        {
            HttpContext.Current.Session["Code"] = new List<string>();
        }
        return HttpContext.Current.Session["Code"] as List<string>;
    }
    set
    {
        HttpContext.Current.Session["Code"] = value;
    }

}



回答2:


This is an oddity in ASP.NET. Whenever you programmatically add items to a collection control (listbox, combobox), you must re-populate the control on each postback.

This is because the Viewstate only knows about items added during the page rendering cycle. Adding items at the client-side only works the first time, then the item is gone.

Try this:

public partial class Main : System.Web.UI.Page
{

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                 Session["MyList"] = new List<string>();
            }   
            ComboBox cbo = myComboBox; //this is the combobox in your page
            cbo.DataSource = (List<string>)Session["MyList"];
            cbo.DataBind();
        }




        protected void cmdAdd_Click(object sender, EventArgs e)
        {
            List<string> code = Session["MyList"];
            code.Add(lstCode.Text);
            Session["MyList"] = code;  
            myComboBox.DataSource = code;
            myComboBox.DataBind();
        }
    }



回答3:


You can't keep values between post backs.

You can use session to preserve list:

// store the list in the session
List<string> code=new List<string>();

protected void Page_Load(object sender, EventArgs e)
{
 if(!IsPostBack)
  Session["codeList"]=code;

}
 // use the list
void fn()
{
 code=List<string>(Session["codeList"]); // downcast to List<string> 
 code.Add("some string"); // insert in the list
 Session["codeList"]=code; // save it again
}


来源:https://stackoverflow.com/questions/10287643/asp-net-with-c-sharp-keeping-a-list-on-postback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!