One of my firends asked me "How can we change the text color for an individual item in a DropDownList or ListBox?". I thought it is a good idea to share the answer with you! The folowing image shows the dropDownList with the solution implemented. As you can see the First two items are red and the rest are black.
To implement it, follow these steps:
-
Put a DropDownList control on your webform: <asp:DropDownList runat="server" Width="200" ID="lstAccounts" />
-
On the Page_Load event handler add the following code
-
// First items (Red)
ListItem listItem1 = new ListItem("100000 (Active)", "100000");
listItem1.Attributes.Add("style", "color: red;");
lstAccounts.Items.Add(listItem1);
-
// Second items (Red)
ListItem listItem2 = new ListItem("100001 (Active)", "100000");
listItem2.Attributes.Add("style", "color: red;");
lstAccounts.Items.Add(listItem2);
-
// Third items (Red)
ListItem listItem3 = new ListItem("123456 (Active)", "100000");
listItem3.Attributes.Add("style", "color: black;");
lstAccounts.Items.Add(listItem3);
-
// ...
You have also control over all attributes which are changable via CSS styles.
You can do the exact same thing with the ListBox object.