[英]List does not grow or cannot add new element to a list in asp.net
I have created a custom type Food
which has 4 attributes name
, weight
, fat
, and calorie
. 我创建了一个自定义类型
Food
,它具有4个属性name
, weight
, fat
和calorie
。 The web application will get name
and weight
from users and calculate the fat
and calorie
. 该Web应用程序将从用户那里获得
name
和weight
,并计算fat
和calorie
。
I have an Add
button to click in order to add a choice to a list. 我有一个
Add
按钮可以单击,以便将选择添加到列表中。
My problem is when I display the message box to check the list, it always show 1
, no matter how many you have added. 我的问题是,当我显示消息框以检查列表时,无论您添加了多少,它始终显示
1
。 Can anyone point out where I am wrong? 谁能指出我做错了什么?
P/S: I tried to display the message box before I add an item to a list and it shows 0
<-- this is true. P / S:在将项目添加到列表之前,我试图显示消息框,并且显示
0
<-这是正确的。
List<Food> foodList = new List<Food>();
Food temp = new Food();
public void addButton_Click(object sender, EventArgs e)
{
//Get weight value from a textbox
temp.weight = Convert.ToDouble(weightTextBox.Text);
//Get name from a provided dropdownlist
temp.name = DropDownList1.Text;
//Add to list
foodList.Add(temp);
//Check the number of elements in the list
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + foodList.Count + "');", true);
}
Every time your page is instantiated, it has an empty foodList
to which you add exactly one item in addButton_Click
. 每次实例化页面时,该页面都会有一个空的
foodList
,您可以在其中精确地在addButton_Click
添加一项。 And a new instance of the page is created to handle each request from the browser, such as request caused by addButton
click. 并创建页面的新实例以处理来自浏览器的每个请求,例如由
addButton
click引起的请求。 You have to implement server-side storage of added items and load them into foodList
every time. 您必须在服务器端实现添加项的存储,并每次将它们加载到
foodList
。
You should move your temp
object creation into addButton_Click
. 您应该将
temp
对象的创建移动到addButton_Click
。 Like this: 像这样:
List<Food> foodList = new List<Food>();
public void addButton_Click(object sender, EventArgs e)
{
Food temp = new Food();
//Get weight value from a textbox
temp.weight = Convert.ToDouble(weightTextBox.Text);
//Get name from a provided dropdownlist
temp.name = DropDownList1.Text;
//Add to list
foodList.Add(temp);
//Check the number of elements in the list
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + foodList.Count + "');", true);
}
Else you're adding the same object all the time. 否则,您一直都在添加相同的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.