2015-09-27 47 views
0

我正在使用C#在Web窗体中工作。我设置了一个数组列表。我有一个按钮,用于将文本框中的用户输入添加到数组列表中。我使用+ =将数组列表打印到标签上。我无法将新条目打印到现有列表中。每次添加时,都会再次打印整个列表。我明白为什么它这样做,但不能包装我的炸脑如何修复代码,所以它会添加一个新的条目而不重复整个列表。将C#Arraylist放入标签中

protected void Button1_Click(object sender, EventArgs e) 
{ 


    ArrayList itemList = new ArrayList(); 
    itemList.Add("red"); 
    itemList.Add("blue"); 
    itemList.Add("green"); 
    itemList.Add(TextBox1.Text); 

    foreach (object item in itemList) 
    { 
     Label1.Text += item + "<br />"; 
    } 



} 

回答

1

只需在for循环前添加Label1.Text =“”即可。

0

开始之前循环做:

Label1.Text = string.Empty; 
2

Don't use the obsolete ArrayList class。使用它的通用版本,List<T>

List<string> itemList = new List<string>(); 
itemList.Add("red"); 
itemList.Add("blue"); 
itemList.Add("green"); 
itemList.Add(textBox1.Text); 

现在你可以用一行更新标签...

Label1.Text = string.Join("<br />", itemList); 

编辑

不幸的是,在这个例子中我使用ArrayList

你仍然可以用一行

Label1.Text = string.Join("<br />", itemList.Cast<string>()); 
+0

不幸的是,在这个例子中我必须使用一个数组列表。 – Blazto

+0

@Blazto查看我的更新 – Eser

+0

谢谢大家所有的例子工作。我在保持arrayList中的前一个条目时遇到了另一个问题。我想我必须声明一个字符串数组并将其存储在那里,但不确定,此刻正在进行试验和错误的事情。 – Blazto

相关问题