C# 将值添加到全局列表
我有以下全球清单-C# 将值添加到全局列表,c#,asp.net,arraylist,C#,Asp.net,Arraylist,我有以下全球清单- public partial class About : System.Web.UI.Page { List<string> changes = null; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { List<string> changes = new List
public partial class About : System.Web.UI.Page
{
List<string> changes = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> changes = new List<string>();
}
因此,我试图将数据列表中所做的所有更改存储到changes
中,以便当用户单击-
protected void Button5_Click(object sender, EventArgs e)
{
List<string> changes = (List<string>)ViewState["array"];
foreach (string text in changes)
{
WebService1 ws = new WebService1();
ws.WebMethod(text);
}
}
protectedvoid按钮5\u单击(对象发送者,事件参数e)
{
列表更改=(列表)视图状态[“数组”];
foreach(更改中的字符串文本)
{
webservice1ws=newwebservice1();
web方法(文本);
}
}
然而,当点击按钮时,我在-changes.add(text)部分得到一个空引用异常。如何存储按钮单击时可用的更改中的所有值?使用
并更改您的List changes=new List()代码>到列表
更改=
空
将此代码添加到构造函数中
if(!IsPostBack)
{
changes = new List<string>();
}
if(!IsPostBack)
{
更改=新列表();
}
另一方面,您可以使用对变量所做的更改在回发后不会持续。您应该将此列表“更改”的值保存到viewstate、会话或应用程序,以便即使在回发之后也可以保留列表的值
更新列表后,将此代码添加到复选框1\u CheckedChanged
事件中
ViewState["Somename"]=changes;
changes= (List<string> )ViewState["Somename"]
在访问列表之前,在按钮5中添加此代码
ViewState["Somename"]=changes;
changes= (List<string> )ViewState["Somename"]
changes=(List)ViewState[“Somename”]
这是一行中断-更改。添加(文本);错误为-NullReferenceException:Object reference未设置为对象的实例。我已对问题@Anandkumar添加了编辑,我得到了一个空引用异常。这只是检索一个值,而不是添加到列表中,每次单击复选框时列表都会被清除。通过使用@Anandkumar solution,我得到了一个空引用异常?