Hey guys,
How do you set the forecolor of a label progmatically???

Dani AI

Generated

A few answers here already show the quick, server-side approach (, ) and using specific color values (, ). Those are fine for small tweaks. For maintainability and consistency on a real site, prefer putting colors in CSS (or a theme/skin) and applying a CSS class to the Label from markup or code-behind. That keeps styling centralized and makes later design changes trivial.

Example: define a class in your stylesheet, then assign that class to the control.

/* site.css */
.label-highlight {
  color: #1E90FF;
  background-color: #000000;
}
protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
    Label1.CssClass = "label-highlight";
}

Notes and best practices:

  • Inline styles generated by setting a server-side color override external CSS, so use CssClass when you want global control.
  • If a color must come from runtime data or user input, validate it and map values to a whitelist of classes rather than injecting raw values.
  • Consider themes/skins for app-wide styling or for per-theme overrides.
  • Accessibility: do not rely on color alone to convey meaning and ensure sufficient contrast (WCAG requires higher contrast for normal text). Add textual cues or icons for status information.

This keeps behavior (code) and presentation (styles) clearly separated, easier to test, and simpler to update across the site.

Recommended Answers

All 4 Replies

For an ASP label in c# code?

Drop a label in the designer:

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Assign a forecolor in code:

protected void Page_Load(object sender, EventArgs e)
    {
      Label1.ForeColor = System.Drawing.Color.Red;
    }

lbl.ForeColor = System.Drawing.ColorTranslator.FromHtml("#9AFE2E");

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

[B]//Reference for setting  color
using System.Drawing;[/B]

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
[B]        Label1.ForeColor = Color.Yellow ;
        Label1.BackColor = Color.Black ;[/B]
    }
}

Hey guys,
How do you set the forecolor of a label progmatically???

Use the following code to change the color of a label

Label1.ForeColor = Drawing.Color.Red
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.