Reputation: 3499
I want to add new items to my generic list when user clicks on a button, but each the the list contains only the last introduced item, it seems that during each button click list get reinitialized :(.
This is a part of code:
List<ProdusBon> listaProduseBon = new List<ProdusBon>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
listaProduseBon.Add(new ProdusBon(-1, Int32.Parse(TextBox2.Text), -1, Int32.Parse (ListBox1.SelectedValue)));
}
I also tried using this code:
List<ProdusBon> listaProduseBon = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
listaProduseBon = new List<ProdusBon>();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
listaProduseBon.Add(new ProdusBon(-1, Int32.Parse(TextBox2.Text), -1, Int32.Parse (ListBox1.SelectedValue)));
}
but in this case a null reference exception was raised.
I must keep all the items in the list and not only the last one, and when click event was raised a new item to be added to the list.
All the controls in Default.aspx got the default values only the ListBox has "Enable AutoPostBack" set to true but i believe that this is not causing this behavior.
I do not how to keep the items in the list in these conditions, please give me a hand if you know how to do this.
Thanks !
Upvotes: 1
Views: 5239
Reputation: 510
On your button click event first bind the list button and then add the new item from the textbox.
protected void Button1_Click(object sender, EventArgs e)
{
//code to bind your list goes here
listaProduseBon.Add(new ProdusBon(-1, Int32.Parse(TextBox2.Text), -1, Int32.Parse (ListBox1.SelectedValue)));
}
Upvotes: 0
Reputation: 2990
Member variables are lost between page loads. You could store the variable in Session if you want it to remain the same value between loads.
List<ProdusBon> listaProduseBon
{
get { return (List<ProdusBon>) Session["ProdusBon"]; }
set { Session["ProdusBon"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (listaProduseBon == null) listaProduseBon = new List<ProdusBon>();
}
protected void Button1_Click(object sender, EventArgs e)
{
listaProduseBon.Add(new ProdusBon(-1, Int32.Parse(TextBox2.Text), -1, Int32.Parse (ListBox1.SelectedValue)));
}
Upvotes: 4