我有一个非常简单的C#程序(用于ASP.Net Web应用程序),它从文本框中获取输入,将其存储在列表中,然后将其显示在列表框中。这是我的代码:
public partial class Form: System.Web.UI.Page
{
List<string> students = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
ListBox.DataSource = students;
}
protected void Display_Click(object sender, EventArgs e)
{
if (this.students.Count != 0)
{
for (int x = 0; x < students.Count; x++)
{
ListBox.Items.Add((x + 1).ToString() + ". " + students[x]);
}
}
}
protected void AddStudent_Click(object sender, EventArgs e)
{
if(tbxStudentInput.Text != "")
{
students.Add(tbxStudentInput.Text);
tbxStudentInput.Text = "";
}
}
}
每次我添加到我的列表,它会覆盖以前的值。当我尝试在列表框中显示存储的值时,它表示计数为0.您是否会告诉我我做错了什么,而不是正确地将值存储在列表中。谢谢
每次,您都会在表单中创建新的学生实例,因为HTTP是无状态的。
尝试移动学生的实例化,即List students = new List();在静态构造函数中
即
static Page()
{
students = new List<string>();
}
理想的方法是从数据库中获取它。