Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# -how to add all system.drwaing.color items in a list?

I'm trying to fill my list with system.drwaing.color items to pick a random color and set it to backColor.

Here is my code:

    List<Color> myList = new List<Color>();
    //rc.Add(Color.Chartreuse);
    //rc.Add(Color.DeepSkyBlue);
    //rc.Add(Color.MediumPurple);
    foreach (Color clr in System.Drawing.Color)
    {
      //error  
    }
    Random random = new Random();
    Color color = myList[random.Next(myList.Count - 1)];
    this.BackColor = color;

Error: 'System.Drawing.Color' is a 'type', which is not valid in the given context

Can anyone give me a Hand?

like image 327
reza Avatar asked Apr 21 '13 11:04

reza


2 Answers

public static List<Color> ColorStructToList()
{
    return typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public)
                        .Select(c => (Color)c.GetValue(null, null))
                        .ToList();
}

List<Color> colorList = ColorStructToList();


private void randomBackgroundColorButton_Click(object sender, EventArgs e)
{
    List<Color> myList = ColorStructToList();
    Random random = new Random();
    Color color = myList[random.Next(myList.Count - 1)];
    this.BackColor = color;
}

public static List<Color> ColorStructToList()
{
    return typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public)
                        .Select(c => (Color)c.GetValue(null, null))
                        .ToList();
}
like image 126
User 12345678 Avatar answered Oct 19 '22 06:10

User 12345678


From this question:

string[] colors = Enum.GetNames(typeof(System.Drawing.KnownColor));
like image 21
Rohit Chatterjee Avatar answered Oct 19 '22 05:10

Rohit Chatterjee