I have a DropDownList on an ASP.NET page that is populated with an SQL database.
<asp:DropDownList ID="ddlName" runat="server"></asp:DropDownList>
In the code, behind the file, it is written:
ddlName.DataSource = SqlDataSource1; ddlName.DataValueField = (this.ddlName.SelectedValue); ddlName.DataTextField = "ccName"; ddlName.DataBind();
I was wondering if it is possible to change the background color or text of an element in the list based on its value?
I just noticed that the example below works when the first page loads, but upon postback, the color of the text disappears, although this is the code. Is something missing?
protected override void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ddlName.DataSource = SqlDataSource5; ddlName.DataValueField = (this.ddlName.SelectedValue); ddlName.DataTextField = "ccName"; ddlName.DataBind(); foreach (ListItem item in ddlName.Items) { if (item.Value == "Item 1") { item.Attributes.Add("style", "color:red"); } if (item.Value == "Item 2") { item.Attributes.Add("style", "color:red"); } } } }
source share