【问题标题】:C# Arraylist into a labelC# Arraylist 变成标签
【发布时间】:2015-12-24 20:20:26
【问题描述】:

我正在使用 Web 表单中的 C#。我设置了一个数组列表。我有一个按钮,可以将文本框中的用户输入添加到数组列表中。我正在使用 += 将数组列表打印到标签上。我无法将新条目打印到现有列表中。每次我添加时,它都会再次打印出整个列表。我理解它为什么这样做,但我现在无法解决如何修复代码,以便它在不重复整个列表的情况下向列表中添加一个新条目。

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 />";
    }



}

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    Don't use the obsolete ArrayList class。使用它的通用版本,List&lt;T&gt;

    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);
    

    编辑

    不幸的是,对于这个例子,我必须使用一个数组列表

    你仍然可以用一行来完成

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

    【讨论】:

    • 不幸的是,对于这个例子,我必须使用一个数组列表。
    • 谢谢大家所有的例子工作。我在将前一个条目保留在 arrayList 中时遇到了另一个问题。我想我必须声明一个字符串数组并将其存储在其中但不确定,目前正在做反复试验。
    【解决方案2】:

    只需在 for 循环之前添加 Label1.Text = ""。

    【讨论】:

      【解决方案3】:

      在开始循环之前,请执行以下操作:

      Label1.Text = string.Empty;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-23
        • 2019-02-06
        • 2014-05-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多