storing and retrieving colors with database, C# windows forms application

jello picture jello · Feb 16, 2010 · Viewed 15.5k times · Source

I'm making a windows application with C#. I'm using the color dialog box for the user to select a color. I'd like to store that color in a database, and be able to retrieve it later on, and be able to use that color in the user interface.

What approach would you suggest to me?

Answer

Chase Florell picture Chase Florell · Feb 16, 2010

The best way will be to store the hex color in a database field nvarchar(7) ... the input would be #ffffff as an example. varchar(6) would work just as well, and take up less space in your DB. Just be sure to append the # in your code.

Since you need to convert it to/from a control color, you can use System.Drawing.ColorTranslator.FromHtml(someHexColor)

// Hex to Control Color
var myColor = "#[color from database]";
var myControlColor = System.Drawing.ColorTranslator.FromHtml(myColor);

// Control Color to Hex
var colorBlue = System.Drawing.Color.Blue;
var hexBlue = System.Drawing.ColorTranslator.ToHtml(colorBlue);