How to change background color of the item in the dropdown


This article describes how to change the background color of the items in a dropdown

Description :


You can change the backcolor and background color of a specific item in a dropdown.
First of all you need need bind the drop then do the coding for changing background color of the items in the dropdown.

Dropdown control:


<asp:DropDownList ID="DropDownList1" runat="server" >
</asp:DropDownList>


Bind the dropdown and change back ground color:


string selectPermission = "select pk_id,ss_code from tablenamewhere ss_code is not null ";//your query
DataTable dtName = SqlHelper.ExecuteDataset(new Connection().GetCon, CommandType.Text, selectPermission).Tables[0];

DropDownList1.DataSource = dtName;
DropDownList1.DataTextField = "ss_code";
DropDownList1.DataValueField = "pk_id";
DropDownList1.DataBind();
//Change background color for alternative items
for (int i = 0; i < DropDownList1.Items.Count; ++i)
{
if (i % 2 == 0)
{
DropDownList1.Items[i].Attributes.Add("style", "background-color:Red");
}
else
{
DropDownList1.Items[i].Attributes.Add("style", "background-color:Blue");
}
}


You can also set the backcolor of the items by


DropDownList1.Items[i].Attributes.Add("style", "backcolor:Red");


You can also search for specific text or value like below:


if (DropDownList1.Items[i].Text == "AA")
{
DropDownList1.Items[i].Attributes.Add("style", "background-color:grey");
}
if (DropDownList1.Items[i].Value == "1")
{
DropDownList1.Items[i].Attributes.Add("style", "background-color:black");
}


Comments

Author: Deepa04 Feb 2010 Member Level: Gold   Points : 0

hi,

Author: macxima16 Feb 2010 Member Level: Gold   Points : 0

Really, this is ok and good example for different back ground colors in ddl

Author: Jayendra Kumar18 Feb 2010 Member Level: Gold   Points : 0

Really, this is working. Thanks to post such a good information



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: