Reputation: 15
I'm using asp.net 4 and C#. I'm having problems adding items to a list via an event from a button click. On the button click I want to read the text from a text box, convert it to an int and add it to the bottom of a List of type int. I then want to display each item in the List in a label. The problem is that it only displays the most recent textbox entry each time. I've spent ages looking at this and trying different things but cant work out what i'm doing wrong. Please can anybody help?
My code is as follows:
namespace CSI
{
public partial class _Default : System.Web.UI.Page
{
string lablelItems;
List<int> numbers = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void AddToSeqBTN_Click(object sender, EventArgs e)
{
int number;
number = Convert.ToInt32(AddNumberTXB.Text);
numbers.Add(number);
printtolabel(numbers);
}
private void printtolabel(List<int> numbers)
{
foreach (int n in numbers)
{
lablelItems += " " + n.ToString();
CurrentSequenceLBL.Text = lablelItems;
}
}
Upvotes: 0
Views: 134
Reputation: 14672
In your handler method
AddToSeqBTN_Click
just do this instead:
CurrentSequenceLBL.Text += " " + Convert.ToInt32(AddNumberTXB.Text);
Upvotes: 1
Reputation: 460158
HTTP is stateless. That means in ASP.NET that all objects are destroyed at the end of the page life-cycle. So as soon as the page is rendered to the client, it won't exist anymore in the server's memory.
So you need to persist the items somewhere.
Nine Options for Managing Persistent User State in Your ASP.NET Application.
Upvotes: 3
Reputation: 7692
The list numbers
is being re-instantiated for each postback your page receives. You must store it's reference somewhere, like on the Session
(at the server) or send it to the ViewState
(to the client).
Also, when you say "add it to the bottom", is it literal? I mean, is the position important to you? Because, if it is, you should use another class, like a Queue
, because List
does not ensure position.
Upvotes: 0