Microsoft has confirmed a bug, saying that the attributes property of ListItem will not work in the DropDownlist(i.e Web server Control).
The alternative for this is to use HTML Server Control
So we then would do is as below:
<SELECT id="DropDownList1" name="DropDownList1" runat="server">
</SELECT>
Using this control we’ll change the background Color of each Item in DropDown.
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!IsPostBack)
{
foreach(FieldInfo col in typeof( KnownColor).GetFields() )
{
if (col.FieldType == typeof(KnownColor) )
{
DropDownList1.Items.Add(new ListItem(col.Name ,col.Name));
}
}
}
for (int i= 0 ;i < DropDownList1.Items.Count;i++)
{
DropDownList1.Items[i].Attributes.Add("style", "background-color:" + DropDownList1.Items[i].Text);
}
}
Make sure to Import the System.Reflections namespace, as well as the System.Drawing namespace, for this example