添加到arrayLists和更改字体颜色

时间:2015-09-28 08:00:48

标签: c#

我正在做家庭作业问题。我必须使用ArrayList。我需要在列表中添加一个项目,并且需要保存它,所以当我添加另一个项目时,它会显示出来。上一个条目没有保存,我应该创建一个字符串数组来保存arraylist吗?当我输入三个颜色名称中的一个时,它应该显示为该颜色。单击添加按钮后,arraylist将打印到标签。指令说要使arraylist静止。(有点困惑,因为静态意味着已经设置不?)这是我到目前为止,请记住我刚刚开始。

 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;

    }
}

1 个答案:

答案 0 :(得分: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/>";
}