How to show dropdown list items in multiple colors in asp.net
Introduction
Some times we need to show items in the dropdown list in different color like example below.

In this article I will show you how you can achieve this by adding a simple css to ListItem attribute.
To explain the article I have taken an example of employees.
I will bind dropdown list with name of employees and color the employee name depending on the name starts from. Ex.
Color Name Starts from
Blue A (“Adam”,”Anamika”,”Ainul”,”Ashish”)
Green K (“Kamran”,”Kiran”,”Kamesh”,”Kasim”)
Red F (“Farhan”,”Feeroz”,”Firan”)
To have a list of items in the dropdown list we need to call a method named GetEmployeeName(), that will return list of Employee objects that contains name of the employees.
Code
public class Employee
{
public Employee()
{
}
public Employee(string EmpName)
{
EmployeeName = EmpName;
}
public string EmployeeName { get; set; }
}
public static List GetEmployeeName()
{
List objEmployeeList = new List();
objEmployeeList.Add(new Employee("Ashish"));
objEmployeeList.Add(new Employee("Kamran"));
objEmployeeList.Add(new Employee("Ashish"));
objEmployeeList.Add(new Employee("Firan"));
objEmployeeList.Add(new Employee("Kiran"));
objEmployeeList.Add(new Employee("Kamesh"));
objEmployeeList.Add(new Employee("Anamika"));
objEmployeeList.Add(new Employee("Farhan"));
objEmployeeList.Add(new Employee("Ainul"));
objEmployeeList.Add(new Employee("Adam"));
objEmployeeList.Add(new Employee("Kasim"));
objEmployeeList.Add(new Employee("Feeroz"));
objEmployeeList.Add(new Employee("Roshan"));
objEmployeeList.Add(new Employee("Depika"));
return objEmployeeList;
}
To color items in the dropdown list depending on the name of the employee we need to call a method FillDropDownList(DropDownList ddlEmployee, string ListItemColor, string NameStartsFrom)
public void FillDropDownList(DropDownList ddlEmployee, string ListItemColor, string NameStartsFrom)
{
var EmployeeList = from EmpList in GetEmployeeName()
where EmpList.EmployeeName.StartsWith(NameStartsFrom)
select new {EmpName= EmpList.EmployeeName};
ListItem lstEmployee;
foreach (var Emp in EmployeeList)
{
lstEmployee = new ListItem(Emp.EmpName);
lstEmployee.Attributes.Add("style","color:"+ ListItemColor);
ddlEmployee.Items.Add(lstEmployee);
}
}
In the method FillDropDownList(), I have further called a method GetEmployeeName() that returs a list of all employees and from that list I have filtered employees whose name starts from name specified in the variable NameStartsFrom.
After filtering the employees I have added those employees in the dropdown list and have added color specified in the variable ListItemColor. In the code you can see in the ListItem object’s arrtibute I have added style attribute and assign color to the specified color. This way we can add color to the dropdownlist item.
Enjoy Coding………..