2012-04-23 68 views
6

我的情况是这样的:我有这些列表的数据插入到他们当他们按下一个添加按钮,但我想回发列表被重新归零。你如何保留它们?我一直在寻找答案,但我想我不太明白如何使用会话,等等。ASP.net与C#保留回发列表

我对ASP.net很新,并没有比C#好多了。

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); 
} 
+0

当你说名单,你的意思'ListView'控制,还是其他什么东西? – SouthShoreAK 2012-04-23 20:23:32

+0

@SouthShoreAK他的意思是通用列表:'列表' – Khan 2012-04-23 20:24:28

回答

14

只要使用这个属性来存储信息:

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

据我所知,这是最好的方法。 – 2012-04-23 20:29:35

+0

不知道如何使用它。 – 2012-04-23 21:00:22

+0

@JakeGaston只需将此属性复制到您的Main类中即可。而不是你的“代码”变量,使用“代码”属性。 – 2012-04-23 21:01:50

3

这是ASP.NET中的一个怪事。无论何时以编程方式将项目添加到集合控件(列表框,组合框),都必须在每次回发时重新填充控件

这是因为Viewstate只知道页面渲染周期中添加的项目。第一次在客户端添加项目时,该项目不见了。

试试这个:

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(); 
     } 
    } 
+0

嘿,谢谢,我会试试看。但是,什么是命名空间(使用System ...)来获取会话关键字的工作? – 2012-04-23 20:59:37

+0

会话不是关键字。它是HttpSessionState类型的属性。你可以像这样访问它HttpContext.Current.Session。 – 2014-07-26 07:16:53

1

你不能把后背上之间的值。

您可以使用session来保存列表:

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