2015-09-28 47 views
0

我正在处理作业问题。我必须使用ArrayList。我需要添加一个项目到列表中,并且需要保存,所以当我添加另一个项目时,它会显示出来。以前的条目不是保存,我应该创建一个字符串数组来保存ArrayList?当我输入三种颜色名称之一时,它应该显示为该颜色。点击添加按钮后,ArrayList打印出标签。该指示说,使静态的ArrayList(由有点困惑,因为静态方法已设置没有?)这是我到目前为止,请记住,我是刚刚开始。添加到arrayLists并更改字体颜色

using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

public partial class _Default : System.Web.UI.Page 
{ 

    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 

    protected void AddButton_Click(object sender, EventArgs e) 
    { 

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

    string textToDisplay = string.Empty; 

    foreach (object item in itemList) //Getting an error here at the "in" 
    { 
     if (TextBox1.Text.StartsWith("red")) // Should I use a switch statement? 
     { 
      itemList[0] = System.Drawing.Color.Red; 
     } 
     if (TextBox1.Text.StartsWith("blue")) 
     { 
      itemList[1] = System.Drawing.Color.Blue; 
     } 
     if (TextBox1.Text.StartsWith("green")) 
     { 
      itemList[2] = System.Drawing.Color.Green; 
     } 

      textToDisplay += item + "<br />"; 
     } 

     ResultLabel.Text = textToDisplay; 

    } 
} 
+0

什么是你得到了该行的错误'的foreach(对象项itemList中)'? – Sybren

+0

你正在创建数组里面的方法,它应该在保留之前的变化的函数之外。 –

+0

以下是错误:类型的异常“System.InvalidOperationException”出现在mscorlib.dll但在用户代码中没有处理 其他信息:集合已修改;枚举操作可能不会执行。 – Blazto

回答

3

你不能每次按钮Add被点击,因为它总是有4种颜色的最大值和顺序是固定的(红,蓝,绿,1种更多的色彩)的时间初始化数组。

可以代替你循环foreach(string item in itemList)foreach(object item in itemList)

您可以使用此代码来添加新颜色的ResultLabel

protected void AddButton_Click(object sender, EventArgs e) 
{ 
    string colorAdded = ""; 
    switch(TextBox1.Text) { 
     case "red": 
      colorAdded = System.Drawing.Color.Red; 
      break; 
     case "blue": 
      colorAdded = System.Drawing.Color.Blue; 
      break; 
     case "green": 
      colorAdded = System.Drawing.Color.Green; 
      break; 
     default: 
      colorAdded = //Insert your default color here; 
      break; 
    } 

    ResultLabel.Text += colorAdded + "<br/>"; 
}