Convert a drawing. Colors to HTML color value

I asked a question about this already, but I incorrectly formulated it.

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

What I want is to set the html attributes using this when the page loads. For example,

 <html> <body bgcolor="#GetRandColor()"> <h1>Hello world!</h1> </body> </html> 
+6
source share
5 answers

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

Your method should look like this:

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

And you can set the background of your form like this:

 <body style="background-color:<%=GetRandColor()%>;"> 
+13
source

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.

+2
source

You can do this with an inline expression: Inline expressions in the .NET Framework

Display expression (<%= ... %>)

 bgcolor="<%= System.Drawing.ColorTranslator.ToHtml(GetRandColor()) %>" 
+2
source
 public string GetRandHtmlColor(){ System.Drawing.Color c = GetRandColor(); return System.Drawing.ColorTranslator.ToHtml(c); } 
0
source

You can use ColorTranslator to convert the value of the Drawing.Color color to HTML. For instance,

 System.Drawing.Color c = System.Drawing.ColorTranslator.FromHtml("#F5F7F8"); String strHtmlColor = System.Drawing.ColorTranslator.ToHtml(c); 

This link will also help you: msdn.microsoft.com/en-us/library/system.drawing.colortranslator.fromhtml.aspx

0
source

All Articles