I’m making a web app in Asp.Net using c# that lets you add items into the list.
My problem is that each time that i click the button to add a new item into the list , its just shows me the last item and the list counter shows me only 1 .
What am I doing wrong??
Here is the code :
public partial class home : System.Web.UI.Page
{
List<string> messageboxs = new List<string>();
public string val = "";
public string data = "";
protected void Button1_Click(object sender, EventArgs e)
{
val = "";
messageboxs.Add(text1.Text);
ListBox1.DataSource = messageboxs;
ListBox1.DataBind();
val = messageboxs.Count.ToString();
}
}
You should read up on ASP.NET Page Life Cycle Overview. In a nut shell, everytime you click the button it causes the page to postback which creates a new instance of the page. You are initializing an empty list on each instance of that page therefore when you come to adding the new item into the list…it’s empty again.
What you need to do is store
messageboxssomewhere which will allow it to persist across postbacks. For your particular example, you could use the ViewState e.g.