I recently got an email from a visitor who was completely stumped with a seemingly
simple issue. He was letting users define their own color schemes and seemed to be
getting random errors. Come to find out he had filled his color selection
controls by hand and had a few misspellings. Whenever you're letting users
choose something from a defined list it's always best to check that the choice
they make is actually on the list.
In this case the solution was simple... we simply fixed the spelling errors, but
unfortunately it's not always something so simple.
In this day and age, you should really validate all user input... even something as
seemingly benign as color selections. Fortunately there's an extremely simple
way to do this for colors. The Color object has a method called IsKnownColor which
returns True if the color is a predefined color and False if it's not.
Take a look at the code listing below for a simple example of its usage.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myColor As Drawing.Color
myColor = Drawing.Color.FromName("Gray")
If myColor.IsKnownColor() Then
myLabel.ForeColor = myColor
myLabel.Text = "This text is " & myColor.Name
End If
End Sub
Note: On a related note... notice that it's "Gray" and not "Grey".
What's even odder is that even though browsers all tend to use "LightGrey",
.NET still prefers "LightGray", and yet passes the color back to
browsers as "LightGrey"! Take a look at this output generated from the code
snippet above if you change the color to "LightGray".
<span id="myLabel" style="color:LightGrey;">This text is LightGray</span>
No wonder that call it a grey area!
If you have a tip you would like to submit, please send it to:
webmaster@asp101.com.