Quantcast
Viewing all articles
Browse latest Browse all 10

HTML Named Colors + Hex Using Reflection

This sample actually shows several things, like how to add controls to a page/Placeholder, dynamically, how to get a color from RGB, convert a color to Hex, plus (the main point) it shows how, using reflection, you can iterate through the system colors and display them (using dynamic labels), plus get the HTML hex for each color.

<%@ Import Namespace="System.Reflection" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>

<script language="VB" Runat="server">
	Sub Page_Load(Source as Object, E as EventArgs)
        Dim t As Type = GetType(Color)
        For Each fi As PropertyInfo In t.GetProperties
            If (fi.PropertyType.ToString = "System.Drawing.Color") Then
                Dim colorName As String = fi.Name
                Dim lbl As Label = New Label
                Dim lit As LiteralControl = New LiteralControl
                Dim c As Color = System.Drawing.Color.FromName(colorName)
                lit.Text = ("&nbsp; " + colorName + " (" & GetHexColor(c) & ")")
                lbl.BackColor = c
                lbl.Width = Unit.Pixel(125)
                lbl.Height = Unit.Pixel(20)
                lbl.BorderColor=Color.FromArgb(&H78E0E0E0)
                lbl.BorderWidth = Unit.Pixel(1)
                phl.Controls.Add(lbl)
                phl.Controls.Add(New LiteralControl(" "))
                phl.Controls.Add(lit)
                phl.Controls.Add(New LiteralControl("<br />"))
            End If
        Next
    End Sub

    Function GetHexColor(colorObj as Color) as String
		return "#" & CheckZero(Hex(colorObj.R)) & CheckZero(Hex(colorObj.G)) & CheckZero(Hex(colorObj.B))
	End function

	Function CheckZero(sNum as String) as String

		if sNum="0" then
			return "00"
		else
			return sNum
		End If

	End Function
</script>
<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 5.0">
		<title>System Colors Using Reflection</title>
	</head>
	<body>
		<form id="form1" Runat="server">
			<asp:PlaceHolder ID="phl" runat="server"></asp:PlaceHolder>
		</form>
	</body>
</html>

Viewing all articles
Browse latest Browse all 10

Trending Articles