Search code examples
c#.netwindowswinformsdarkmode

When changing form background color I'm getting the indexer is read only error


I am trying to make a dark mode for my Windows forms app but am getting and error. Never set any property of my form to read only neither can I find and option to set it to read only

public void TemniNacin()
        {
            LetalskaDruzba.DefaultBackColor = Color.Black;
            foreach (var textboxi in Controls.OfType<TextBox>())
            {
                textboxi.BackColor= Color.Black;
                textboxi.ForeColor = Color.White;
            }
        }

error is happening in the 3rd line


Solution

  • The Control.DefaultBackColor Property is declared as

    public static System.Drawing.Color DefaultBackColor { get; }
    

    I.e., it is a read-only property.

    You can see this if you hover your mouse-cursor over the property. Visual Studio will then show you this declaration in a tool-tip:

    enter image description here

    You can assign this color to the form instance instead:

    BackColor = Color.Black;
    

    I assume that this code is inside a Form and that LetalskaDruzba is the form name. Then you can access the properties, fields and methods of this form directly. No need to prepend it a this. as in this.BackColor = Color.Black;.