The "Color.Name" property or indexer cannot be assigned, as it is read-only

Asked

Viewed 448 times

0

Follow code where I define SegundaTela:

public partial class Form1 : Form
{
    SegundaTela telaSecundaria;
}

Code:

telaSecundaria = new SegundaTela();
telaSecundaria.label_segunda_tela.BackColor.Name = cor_fundo;

I get error:

CS0200 The "Color.Name" property or indexer cannot be assigned, as it is read-only

Some solution?

2 answers

5


The error is self descriptive, you cannot change the color name. Why do you want to change its name? This makes no sense.

If you want to change the color, just change the color, don’t change its name. The solution is not to do this.

Documentation.

So you can do:

telaSecundaria.label_segunda_tela.BackColor = cor_fundo;

I am assuming that cor_fundo is a variable of type Color. If it’s not this would be a mistake because the property BackColor expect this. If it’s a string with the name can use the FromName() (obviously needs to be one of the strings registered on framework to work. So I would do something like this:

var cor_fundo = Color.FromName("Blue");

Example:

using static System.Console;
using System.Drawing;

public class Program {
    public static void Main() {
        Color slateBlue = Color.FromName("SlateBlue");
        WriteLine($"Slate Blue has these ARGB values: Alpha:{slateBlue.A}, red:{slateBlue.R}, green: {slateBlue.B}, blue {slateBlue.G}");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

3

If you want to change the color of label. The property you need to work on is the ForeColor and if you want to change the background color, it is not assigning the Name you can, just assign the struct value Color the property BackColor:

See how it would look:

telaSecundaria = new SegundaTela();
telaSecundaria.label_segunda_tela.BackColor = Color.Red;
telaSecundaria.label_segunda_tela.ForeColor = Color.White;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.