Live Chat Icon For mobile
Live Chat Icon

How to apply css style to each item of the dropdownlist or listbox control

Platform: ASP.NET| Category: Dropdownlist

The dropDownList has a bug which prevent us from assigning the style property to each item in the DropDownList.
This bug confirmed by Microsoft in Microsoft Knowledge Base Article – 309338
For the workaround use a HTML dropdownlist with runat=server tag


<SELECT id='DropDownList1' runat='server' >
</SELECT>

Use namespace System.Reflection
VB.NET


If Not Page.IsPostBack Then
Dim col As FieldInfo
For Each col In GetType(KnownColor).GetFields
	If col.FieldType Is GetType(Drawing.KnownColor) Then
		DropDownList1.Items.Add(New ListItem(col.Name, col.Name))
	End If
Next
End If

Dim i As Integer
For i = 0 To DropDownList1.Items.Count - 1
	DropDownList1.Items(i).Attributes.Add('style', 'background-color:' + DropDownList1.Items(i).Text)
Next

C#


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);
}

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.