Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / XHTML

Keeping the listitem color of a DropDownList during postback

4.67/5 (3 votes)
11 Jun 2009CPOL1 min read 32.8K   262  
Keeping the styles that you apply to a dropdownlist during postback; the article focuses on color styles.

Introduction

Sometimes you may need to apply styles to the list items of a DropDownList, but these keep only until a postback occurs. The example I present is a list of products where the red items are those that have been saved.

Using the code

In the ASPX page you have a DropDownList to apply colors, a HiddenField is added in which you store the indices of the list items that have a color.

ASP.NET
<asp:HiddenField ID="hfValuesSelectForColor" runat="server" />
<asp:DropDownList ID="drpProduct" runat="server" 
     DataTextField="Text" DataValueField="Value" ><asp:DropDownList/>

It also requires a JavaScript function that is responsible for coloring the DropDownList as the indices stored in hfValuesSelectForColor; this function is between the head tags.

ASP.NET
<head runat="server">
<title>DropDownListColor</title>
<script language="javascript" type="text/javascript">
<!--
//DESCRIPTION: Keep the colors of a dropdownlist during postback
//DrpName: Name of the dropdownlist who need to keep the colors during postback
//Color: Color to apply in the dropdownlist
//StyleType: Style to apply in the dropdownlist COLOR or BACKGROUND-COLOR
//indicesForSplit: string with the list of index
//                 of the items of the dropdownlist who has color
//SeparatorSplit: A char to disjoin the items of the string indicesParaSplit
function drpSetColors(DrpName, Color, StyleType, indicesForSplit, SeparatorSplit) 
{
  if (document.getElementById(DrpName) != null) {
      var indices = indicesForSplit.split(SeparatorSplit);
    if (indices[0] == "")
        return;
    for (j = 0; j < indices.length; j++) {
     if (StyleType.toUpperCase() == "COLOR")
      document.getElementById(DrpName).options[indices[j]].style.color = Color;
     else if (StyleType.toUpperCase() == "BACKGROUND-COLOR")
     document.getElementById(DrpName).options[indices[j]].style.backgroundColor = Color;
    }
  }
}
-->
</script />

In the code-behind in Page_load, you need to call a JavaScript function. To construct the sentence, I use a StringBuider (needs to add the namespace System.Text), but you can use a simple string.

C#
protected void Page_Load(object sender, EventArgs e)
{
    //call the javascript function to keep the color of the dropdownlist
    StringBuilder drpSetColors = new StringBuilder();
    drpSetColors.Append("<script>");
    drpSetColors.Append("drpSetColors('DrpProduct', 'Red', 'color', '" + 
                        hfValuesSelectForColor.Value + "','|');");
    drpSetColors.Append("</script>");
    //For Visual 2008 with Ajax we use ScriptManager not clientScript.
    //ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), 
    //       "drpColor", drpSetColors.ToString(), false);
    this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), 
                           "drpColor", drpSetColors.ToString());
}

You already have everything you need in order to keep the colors, now you only need to indicate which items are colored. For that, I work in the code-behind, assuming you have more development on the server than the client, and therefore needs to keep the colors of the items in the list in a postback.

To accomplish this, you must have stored somewhere, the reason for coloring the items in the list. In my example, I am extracting data from a Viewstate which contains a datatable with three columns Text, Value, and IsSave. The columns Text and Value are the DataTextField and DataValueField for the DropDownList, and IsSave is a value that indicates if you must color an item (product) when it is saved.

C#
DataTable dt = (DataTable)ViewState["vsTable"];
            
hfValuesSelectForColor.Value = "";
//search for the elements you must colored and add to hfValuesSelectForColor
DataRow[] drColors = dt.Select("IsSave = 1");
for (int i = 0; i < drColors.Length; i++)
{
    int index = drpProduct.Items.IndexOf(
      drpProduct.Items.FindByValue(drColors[i]["Value"].ToString()));
    drpProduct.Items[index].Attributes.Add("style", "color: red");
    drpProductCopy.Items[index].Attributes.Add("style", 
                         "background-Color: red");
    drpProductCopy.SelectedIndex = index;
    if (hfValuesSelectForColor.Value == "")
        hfValuesSelectForColor.Value = index.ToString();
    else
        hfValuesSelectForColor.Value = hfValuesSelectForColor.Value + "|" + inde;
}

Points of interest

Well, that's all there is to it. To complete the code, you need to download the source... I hope you take this hint useful.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)