June 2008 - Posts

Alternating colors on DropDownList, ListBox and other ListControl.

My former colleague asked me if it is possible to attach an alternating color to a DropDownList control, similar with the GridView’s alternating rows.
I found out that you can achieve that, by setting the background-color of the ListItem using  “style” attributes.

Here is the code.
    /// <summary>
    /// A method that attach alternating colors
    /// to a ListControl. e.g (DropDownList, ListBox,
    ///
    /// </summary>
    /// <param name="listControl"></param>
    /// <param name="itemColor"></param>
    /// <param name="alternatingColor"></param>

    private void AttachColor(ListControl listControl,string itemColor,string alternatingColor)
    {       
        string color = itemColor;

        foreach (ListItem li in listControl.Items)
        {
            color = (color == itemColor) ? alternatingColor : itemColor;
            li.Attributes["style"] = " background-color: " + color;
        }       
    }


You can use it in your existing ListControl.

AttachColor(myListBox, "white", "lightblue");
AttachColor(myDropDownList, "white", "lightblue");

 

Sample ScreenShot:

Posted by n.ocampo with no comments
Filed under: , , ,