have a 1 dropdownlist. And data in dropdownlist will be
0. - USA
1. - - Florida
2. - - - Boca Raton
and so on..... , Now for ur info USA in Country , Florida is region, and Boca Raton is city.
I want to show USA in different color. I tried DropDownList's listitem attribute.add("style","color:green") but it does not work.
Adding attributes to ListItem in DropDownList but it won't work because DropDownList and ListBox ignores those attributes (don't ask me why).
One possible way you can do is way using html select server control, I have listed code that will display list in the way you want, Instead of loading from database I am loading from array list you can loop through your dataset in same way.
run online sample ------------------------------------------------
Source code for DropDownList With Color
------------------------------------------------
<%@ Page Language="C#"%>
<%@ Import Namespace="System.Drawing" %>
<script runat="server">
void Page_Load(object sender, EventArgs e){
if(!IsPostBack){
ArrayList ds = GetData();
foreach(MyData data in ds){
ListItem item = new ListItem(data.Text,data.Value);
item.Attributes.Add("style", "color:" + data.Color);
MyDropDown.Items.Add(item);
}
}
}
public ArrayList GetData(){
System.Collections.ArrayList data = new System.Collections.ArrayList();
data.Add(new MyData("Usa","Usa","Red"));
data.Add(new MyData("-Florida","-Florida","Blue"));
data.Add(new MyData("--Boca Raton","--Boca Raton ","Green"));
data.Add(new MyData("India","India","Red"));
data.Add(new MyData("-Gujarat","-Gujarat","Blue"));
data.Add(new MyData("--Ahmedabad","--Ahmedabad","Green"));
return data;
}
publicclass MyData{
privatestring _Text;
privatestring _Value;
privatestring _Color;
publicstring Text{get{ return _Text;}}
publicstring Value{get{ return _Value;}}
publicstring Color{get{ return _Color;}}
public MyData(string text,stringvalue,string color){
_Text = text;
_Value = value;
_Color = color;
}
}
void MyDropDown_ServerChanged(object sender, EventArgs e){
ListItem selectedItem = MyDropDown.Items[MyDropDown.SelectedIndex];
Response.Write(selectedItem.Text);
// Recreate List because loading from viewstate will remove attributes.
MyDropDown.Items.Clear();
ArrayList ds = GetData();
foreach(MyData data in ds){
ListItem item = new ListItem(data.Text,data.Value);
item.Attributes.Add("style", "color:" + data.Color);
MyDropDown.Items.Add(item);
}
}
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<%-- onchange client side event will fire OnserverChange --%>
<SELECT id="MyDropDown" onchange="document.forms[0].submit()"
OnServerChange="MyDropDown_ServerChanged" runat="server" />
</form>
</body>
</html>