C# Button Text Condition
Using a WinApp form in c#, and many buttons here...
I want to create a condition, that if a button has text in it, then the background color of that button changes. That sounds easy enough to do. But what I have is a common set of buttons, that have text in them dependant of values in a XML document.
Example: Week 1 - Buttons 1, 3 and 5 have text in them. Week 2 - Buttons 2 and 3 have text.
How can I setup a sep开发者_StackOverflowerate condition to check if the button has text in it or not, and then change the color if there is a text value in the button.
Thank you.
I would extend button and override the label setter such that it also changes the color when setting the contents of the label to some non-empty value.
Do you want something like this?
foreach (var btn in this.Controls.OfType<Button>()) {
btn.BackColor = (string.IsNullOrEmpty(btn.Text))
? SystemColors.ButtonFace : Color.AliceBlue;
}
I would put it in a method, and call it on form load, or whenever the buttons' texts changes.
精彩评论