I have the following global 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>();
}
I am trying to add string values to changes like so –
protected void CheckBox1_CheckedChanged(Object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
DataListItem item = (DataListItem)chk.NamingContainer;
TextBox txt = (TextBox)DataList1.Items[item.ItemIndex].FindControl("aliasTextBox");
string text = txt.Text;
changes.Add(text);
ViewState["array"] = changes;
}
So I am trying to store all changes made in the dataList into changes so that when a user clicks –
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);
}
}
However when it comes to clicking the button, I get a null reference exception on the – changes.add(text) section. How can I store all the values in changes to be available on button click?
The changes that you are making to a variable will not persist after the postback. You should save the value of this list ‘changes’ to a viewstate, session or application so that you can retain the values of the list even after the postback.
Add this code in the
CheckBox1_CheckedChangedevent after updating the listAdd this code in the
Button5_Clickbefore accessing the list