Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net with C# Keeping a List on postback

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);
}
like image 444
Jake Gaston Avatar asked Apr 23 '12 20:04

Jake Gaston


1 Answers

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

}
like image 91
Vano Maisuradze Avatar answered Oct 11 '22 00:10

Vano Maisuradze