Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Drawing.Color into HTML color value

Tags:

html

c#

asp.net

I asked a question about this already, but I wrong-phrased it.

I have a method GetRandColor() on the server that returns a System.Drawing.Color object.

What I want is to be able to set html attributes using this when the page loads. So as an example,

<html>
<body bgcolor="#GetRandColor()">
<h1>Hello world!</h1>

</body>
</html>
like image 522
Hithere Paperbag Avatar asked Jan 09 '13 05:01

Hithere Paperbag


2 Answers

You can't return a System.Drawing.Color object from your function because browsers only understand text. So instead, you should return the string representation of the color, be in RGB, HEX format or what have you.

Your method then should look like this:

 protected string GetRandColor()
 {
     return ColorTranslator.ToHtml(Color.Red);
 }

And you can set the background of your form as so:

<body style="background-color:<%=GetRandColor()%>;">
like image 123
Icarus Avatar answered Sep 25 '22 07:09

Icarus


If GetRandColor() is in a static class, this should work:

<body bgcolor="<%= System.Drawing.ColorTranslator.ToHtml(ClassName.GetRandColor()) %>">

You may need to add the class' namespacess before the class name.

like image 25
JLRishe Avatar answered Sep 25 '22 07:09

JLRishe