I have a TextBox
which is set to be ReadOnly.
At some point that TextBox is being available for editing, and it's BackColor changes (It is indicating if the value is valid).
If I want To set the Texbox back to ReadOnly, the TextBox doesn't get back the original BackColor that a ReadOnly TextBox gets.
What should I do in order to get the original color again?
I realize I can set the color manually to SystemColors.Control
, but is this the "Right way"?
Code Sample
This is a simple code for demonstration.
If SystemColors.Control is the way to go, i will change it in the ReadOnlyChanged
Event...
private void button1_Click(object sender, EventArgs e)
{
//At this point this.textBox1 is ReadOnly
this.textBox1.ReadOnly = false;
this.textBox1.BackColor = Color.Orange;
/*this.textBox1.BackColor = SystemColors.Control;*/ //Is this the right way?
this.textBox1.ReadOnly = true; //Textbox remains orange...
}
I know this is an old question, but for posterity sake:
TextBox as well as many other controls rely on Color.Empty to decide whether or not to display its default color.
To set a TextBox back to the system default (irregardless of state):
Yes, that's fine. There's no reason you can't use the SystemColors to specify the desired color for the control. I've never heard of anything in
WinForms
that would cause a control to automatically revert to its default color upon settingReadOnly = true
.I suppose one alternative is to create a class-level variable called
textBox1OriginalColor
or something and set it in the form'sLoad
event. Then you know exactly what it was when the form was originally displayed, if you think someone might in the future set the text box's default background color to, say, blue in the designer or something.You have to set
BackColor
to the look of aReadOnly TextBox's BackColor
, that isColor.FromKnownColor(KnownColor.Control)
:You may need a variable to store the current BackColor every time your TextBox's BackColor changes: