I have an in my form, with 4 different options (items) What I need to do it\'s to set a different color from client side, without PostBack.
This is what worked for me...
ListItem listItem = new ListItem();
listItem.Attributes.Add("style", "background-color: Gold !important;");
listItem.Text = "Apply for funding";
dlPayment.Items.Add(listItem);
This markup applies a different background color to each item, and sets the onchange
event handler:
<asp:DropDownList ID="DropDownList1" runat="server" onchange="SetDropDownListColor(this);">
<asp:ListItem style="background-color: White !important;" >Select...</asp:ListItem>
<asp:ListItem style="background-color: Green !important;" >Complete</asp:ListItem>
<asp:ListItem style="background-color: Yellow !important;" >Running</asp:ListItem>
<asp:ListItem style="background-color: Red !important;" >Waiting in SEV 1</asp:ListItem>
<asp:ListItem style="background-color: Blue !important;" >No Batch</asp:ListItem>
</asp:DropDownList>
The following Javascript ensures that the color of the selection box matches the color of the selected item:
function SetDropDownListColor(ddl) {
for (var i = 0; i < ddl.options.length; i++) {
if (ddl.options[i].selected) {
switch (i) {
case 0:
ddl.style.backgroundColor = 'White';
return;
case 1:
ddl.style.backgroundColor = 'Green';
return;
case 2:
ddl.style.backgroundColor = 'Yellow';
return;
case 3:
ddl.style.backgroundColor = 'Red';
return;
case 4:
ddl.style.backgroundColor = 'Blue';
return;
}
}
}
}
The !important
modifier is set in the markup of the items in the list, in order to override the background color set to the whole control in the Javascript function.
In order to preserve the color of the DropDownList after a postback, the following line of code can be added to the Javascript block. It defines a handler for the load
event of the page, in which the color of the selected item is applied to the selection box:
window.addEventListener('load', function () { SetDropDownListColor(document.getElementById('<%= DropDownList1.ClientID %>')); }, false);
Try out the following code
In the filename.aspx.cs file...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
System.Drawing.Color c1 = new System.Drawing.Color();
Type t = c1.GetType();
int row;
foreach (System.Reflection.PropertyInfo p1 in t.GetProperties())
{
ColorConverter d = new ColorConverter();
try
{
DropDownList2.Items.Add(p1.Name);
for (row = 0; row < DropDownList2.Items.Count - 1; row++)
{
DropDownList2.Items[row].Attributes.Add("style",
"background-color:" + DropDownList2.Items[row].Value);
}
}
catch
{
// Catch exceptions here if needed
}
}
}
}