Click here to Skip to main content
Click here to Skip to main content

ASP.NET Combobox dropdownlist with Images

, 1 Oct 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
An ASP.NET combobox dropdownlist with images, Internet Explorer/Firefox/Opera compatible
Static mode DropdownlistImage

drop.JPG

Dynamic mode DropdownlistImage with dynamic databinding

drop.JPG

Introduction

It's very difficult to find a free and compatible (with all browsers) dropdownlist that can contain image and text. However, I looked at the jQuery open source components and saw that jQuery developers have done an excellent work with their several widgets that they have developed. jQuery is a powerful JavaScript framework with very beautiful and optimized widgets.

I found an example of their dropdownlist image in a simple HTML page, and I decided to try to create a scalable HTML control that encapsulates this dropdownlist. The URL of the simple example is http://marghoobsuleman.com/jquery-image-dropdown.

Using the Code

The base component is a very simple basic HtmlSelect (System.Web.UI.Htmlcontrols namespace). I extended this class to add the specific behaviour.

At the beginning, I added the resources of the component in the assembly (JavaScript files, CSS file, and the arrow image of my extended HtmlSelect class). I added these resources on the override of the PreRender method, and I added the references in the AssemblyInfo.cs file. Here is the Microsoft recommendation for that. All these resources must be "embedded resources".

The following code shows you a special case: how to display a picture embedded in an assembly and call it in CSS code. In the beginning, the arrow image of the HtmlSelect is referenced in dd.css like this:

.dd .ddTitle span.arrow 
{ 
  float:right; 
  display:inline-block; 
  width:16px; 
  height:16px; 
  cursor:pointer;
  background-image:url('arrow_d.gif');
}

ASP.NET is not able to display arrow_d.gif with this declaration, because the URL of the picture is not arrow_d.gif. If you want to display this picture, you must follow three steps:

Step 1: You must get the image URL with the GetWebResourceUrl method of the ClientScript object like this:

//get url of embedded image
string urlImageArrowCombo = Page.ClientScript.GetWebResourceUrl(this.GetType(), 
                            "AssemblyName.dd_arrow.gif");

(In this example, the picture is at the root of the assembly). If the picture was in an assembly directory called "toto", "AssemblyName.dd_arrow.gif" would become "AssemblyName.toto.dd_arrow.gif".

Step 2: Extract the CSS code of the CSS file and put it in the server side to inject the image URL in the style:

string urlImageArrowCombo = 
   Page.ClientScript.GetWebResourceUrl(this.GetType(), "ComboImg.dd_arrow.gif");

StringBuilder strStyleArrow = new StringBuilder();

strStyleArrow.Append(" .dd .ddTitle span.arrow { ")
   .Append(" float:right; ")
   .Append(" display:inline-block; ")
   .Append(" width:16px; ")
   .Append(" height:16px; ")
   .Append(" cursor:pointer; ")
   .Append(" background-image:url('" + urlImageArrowCombo + "');")
.Append(" } ");

HtmlGenericControl styleArrow = new HtmlGenericControl("style");
styleArrow.Attributes.Add("type", "text/css");

jqdd.Controls.Add(
    new LiteralControl(strStyleArrow.ToString())
);

Page.Header.Controls.Add(styleArrow);

Last step: If there are lots of HtmlSelect images in the same page, the style that you add in the header of the page must be shared by all HtmlSelect image controls. So, the test Page.Items.Contains("styleAlreadyPut")) is necessary, to add the style once. The OnPreRender event is to add resources like I just explained. Here is the code:

/// Test if the Script manager is not missing
/// for the Sys.WebForms.PageRequestManager manipulation in prerender event
/// and load script and css
protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);

    if (!this.DesignMode)
    {
        // Test for ScriptManager and register if it exists
        // we need it for PageRequestManager manipulation in prerender
        ScriptManager sm = ScriptManager.GetCurrent(Page);

        if (sm == null)
            throw new HttpException("A ScriptManager control " + 
                                    "must exist on the current page.");

        //Add js and css files resource
        string cssdd = Page.ClientScript.GetWebResourceUrl(GetType(), 
                            "ComboImg.dd.css");
        string scriptJQuery = Page.ClientScript.GetWebResourceUrl(this.GetType(), 
                                   "ComboImg.jquery-1.3.2.min.js");
        string scriptJQuerydd = Page.ClientScript.GetWebResourceUrl(this.GetType(), 
                                   "ComboImg.jquery.dd.js");

        HtmlLink lnk = new HtmlLink();
        lnk.Href = cssdd;
        lnk.Attributes["rel"] = "stylesheet";
        lnk.Attributes["type"] = "text/css";

        HtmlGenericControl jq = new HtmlGenericControl("script");
        jq.Attributes.Add("language", "JavaScript");
        jq.Attributes.Add("type", "text/javascript");
        jq.Attributes.Add("src", scriptJQuery);
        jq.Attributes.Add("alt", "scriptJQuery");

        HtmlGenericControl jqdd = new HtmlGenericControl("script");
        jqdd.Attributes.Add("language", "JavaScript");
        jqdd.Attributes.Add("type", "text/javascript");
        jqdd.Attributes.Add("src", scriptJQuerydd);
        jqdd.Attributes.Add("alt", "scriptJQuerydd");

        Page.Header.Controls.Add(jq);
        Page.Header.Controls.Add(jqdd);
        Page.Header.Controls.Add(lnk);

        //Put one time the style whose gives reference to arrow of the combo
        if (!Page.Items.Contains("styleAlreadyPut"))
        {
            //get url of embedded image
            string urlImageArrowCombo = Page.ClientScript.GetWebResourceUrl
					(this.GetType(), "ComboImg.dd_arrow.gif");

            StringBuilder strStyleArrow = new StringBuilder();

            strStyleArrow.Append(" .dd .ddTitle span.arrow { ")
               .Append(" float:right; ")
               .Append(" display:inline-block; ")
               .Append(" width:16px; ")
               .Append(" height:16px; ")
               .Append(" cursor:pointer; ")
               .Append(" background-image:url('" + urlImageArrowCombo + "');")
           .Append(" } ");

            HtmlGenericControl styleArrow = new HtmlGenericControl("style");
            styleArrow.Attributes.Add("type", "text/css");

            jqdd.Controls.Add(
                new LiteralControl(strStyleArrow.ToString())
            );

            Page.Header.Controls.Add(styleArrow);

            Page.Items.Add("styleAlreadyPut", "styleAlreadyPut");
        }
    }
}

I overrode the OnDataBinding method because the base OnDataBinding of the HtmlSelect does a specific treatment only if DataValueField and DataTextField are defined. (Watch the source code of OnDataBinding with Reflector (it's your best friend Smile | :) ).)

In our case, we don't use these properties because we don't need them and we need to create a ListItem with the values of the bound DataTable. The final point to see is the currentValue property which allows to save the currently selected value before the databinding, to retrieve it afterwards.

///Redefine OnDataBinding of the select
///without DataTextfiled and Datamember properties
protected override void OnDataBinding(EventArgs e)
{
    IEnumerable data = base.GetData();
    currentValue = Value;

    if (data != null)
    {
        DataTable source = ((DataView)data).Table;
        base.Items.Clear();
        ICollection is2 = data as ICollection;
        if (is2 != null)
        {
            this.Items.Capacity = is2.Count;
        }

        foreach (DataRow dr in source.Rows)
        {
            string value = FormatString(dr[0]);
            string imgPath = FormatString(dr[1]);
            string text = FormatString(dr[2]);
            
            ListItem it = new ListItem();
            it.Enabled = true;
            it.Text = text;
            it.Value = value;
            it.Selected = (value.Equals(currentValue));

            base.Items.Add(it);
        }
    }
    Value = currentValue;
    this.ViewState["_!DataBound"] = true;
    this.RequiresDataBinding = false;
}

Using Reflector, I looked at the implementation of the RenderChildren method of the HtmlSelect class. In my case, I made two distinctions:

  • Without data-binding: call the RenderChildren base class.
  • With data-binding: override the RenderChildren implementation to generate option tags with the correct format.

The correct format is "item text".

The conclusion is that if you want to databind this combo, you must provides a DataTable with three columns:

  1. item value
  2. image path
  3. the text of the item

Here is the RenderChildren implementation:

/// Generates options tags
protected override void RenderChildren(HtmlTextWriter writer)
{
    if (DataSource != null)
    {
        if (DataSource.GetType() == typeof(DataTable))
        {
            DataTable source = (DataTable)DataSource;

            if (source.Rows.Count == 0)
            {
                base.RenderChildren(writer);
                return;
            }

            foreach (DataRow dr in source.Rows)
            {
                string value = FormatString(dr[0]);
                string imgPath = FormatString(dr[1]);
                string text = FormatString(dr[2]);
                bool selected = currentValue.Equals(value);

                if (selected)
                    writer.Write("" + text + "");
                else
                {
                    writer.Write("" + text + "");
                }
                writer.WriteLine();
            }
        }
    }
    else
    {
        base.RenderChildren(writer);
    }
}

RenderControl adds a script which allows the initialization of the dropdownlist with the powerful jQuery framework. To initialize the dropdownlist, you must execute the following jQuery statements: $(document).ready(function() { $('#dropdownlistId').msDropDown(); }. But, ASP.NET will encounter JavaScript errors during the loading phase if you execute only these statements.

Arnold Matusz is a jQuery ASP.NET developer, and his solution to use JQuery with ASP.NET is available here. The solution is simple: execute this script at the end of the Request AJAX event.

/// Set the jQuery script for the combo at the beginning of the page request
public override void RenderControl(HtmlTextWriter writer)
{
    base.RenderControl(writer);
    
    StringBuilder scriptInit = new StringBuilder();

    scriptInit.Append(" <script type="\"text/javascript\""> ")
     .Append(" Sys.WebForms.PageRequestManager.getInstance()" + 
             ".add_endRequest(EndRequestHandler); ")
     .Append("    function EndRequestHandler(sender, args) { ")
     .Append("       if (args.get_error() == undefined) { ")
     .Append("            setImageComBo_" + this.ID + "(); ")
     .Append("       }  ")
     .Append("     } ")
     .Append("   function setImageComBo_"+this.ID+"() { ")
     .Append("       $(document).ready(function() { ")
     .Append("               $('#"+this.ID +"').msDropDown();                       ")
     .Append("       });  ")
     .Append("   }  ")
     .Append("   setImageComBo_" + this.ID + "();    ")
     .Append("</script>");

    writer.Write(scriptInit.ToString());
}

Points of Interest

I learned to encapsulate a jQuery component within ASP.NET. I invite you to try developing more jQuery ASP.NET web controls; they are very useful and beautiful...

I look forward to your suggestions.

History

  • 28th September, 2009: Initial post
  • 29th September, 2009: Updated source code

License

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

Share

About the Author

David Zenou
Software Developer Several
France France
I am a Fan of dotnet technologies. I began to work with Java j2ee technologies and today i made my choice : .Net Framework is very pleasant , has excellents article codes and documentation.
I found very useful articles in codeproject , and today i want to give my contribution , and i hope that my articles will be useful.
 
Go to see my blog : http://davidzenou.blogspot.com/2009/01/david.html

Comments and Discussions

 
QuestionFor an updated version of the dropdown PinmemberDewey4-Oct-13 5:51 
QuestionWhere is source code for postback functionality? PinmemberSkippingAdi3-Mar-11 5:34 
GeneralWidth Problem With Safari Pinmembermanofatlantic1-Dec-10 8:04 
Generalsharepoint Pinmemberrangagmail3-Nov-10 22:34 
GeneralRe: sharepoint PinmemberDavid Zenou4-Nov-10 0:47 
GeneralProblems with master page PinmemberMember 189730328-Oct-10 23:31 
GeneralPerformance Pinmembermaha.mahathy4-Sep-10 0:59 
GeneralThanks for the nice article PinmemberMadhanlal JM4-Aug-10 18:40 
GeneralReset Issue. PinmemberViral Upadhyay28-Jun-10 23:30 
GeneralRight Arrow Not Showing [modified] Pinmembermanofatlantic15-Jun-10 6:16 
GeneralRe: Right Arrow Not Showing Pinmembermanofatlantic15-Jun-10 9:00 
GeneralServer.Transfer on dropdown selection Pinmemberkynatic6-Jun-10 2:54 
GeneralGood one! PinmemberSandeep Mewara27-Mar-10 6:21 
GeneralOnChange problem PinmemberMember 15586132-Feb-10 6:51 
Generalgood job PinmemberArlen Navasartian18-Jan-10 22:06 
Questionhow to set "dropdownlist selected" property in page load [modified] PinmemberAnusha Kumar7-Jan-10 11:12 
AnswerRe: how to set "dropdownlist selected" property in page load PinmemberDavid Zenou7-Jan-10 14:36 
GeneralRe: how to set "dropdownlist selected" property in page load [modified] PinmemberAnusha Kumar8-Jan-10 10:01 
QuestionModalPopupExtender Issue PinmemberMember 176675627-Nov-09 3:17 
QuestionData not displaying in DropDownList PinmemberAjatshatru25-Nov-09 20:40 
AnswerRe: Data not displaying in DropDownList PinmemberDavid Zenou25-Nov-09 22:17 
QuestionRe: Data not displaying in DropDownList PinmemberAjatshatru25-Nov-09 22:56 
QuestionThe control doesn't postback? Pinmemberrayprestige22-Oct-09 16:52 
AnswerRe: The control doesn't postback? [modified] PinmemberDavid Zenou24-Oct-09 14:49 
GeneralRe: The control doesn't postback? Pinmemberrayprestige26-Oct-09 17:07 
GeneralRe: The control doesn't postback? PinmemberTer@Byte28-Oct-09 2:58 
GeneralRe: The control doesn't postback? Pinmemberrayprestige3-Nov-09 10:36 
GeneralRe: The control doesn't postback? PinmemberDavid Zenou3-Nov-09 15:14 
GeneralRe: The control doesn't postback? PinmemberDavid Zenou9-Nov-09 14:07 
GeneralRe: The control doesn't postback? PinmemberCaezar Girang9-Sep-10 16:46 
GeneralRe: The control doesn't postback? PinmemberMember 189730331-Oct-10 0:20 
GeneralRe: The control doesn't postback? PinmemberSuren Mkrtchyan5-Feb-11 10:33 
GeneralRe: The control doesn't postback? Pinmembergablu2u17-Aug-11 5:19 
GeneralControl in UserControl Pinmemberjkarnofsky20-Oct-09 10:43 
GeneralRe: Control in UserControl Pinmemberkevin b jenkins21-Oct-09 10:26 
GeneralRe: Control in UserControl PinmemberDavid Zenou24-Oct-09 9:15 
GeneralNo dropdown icon PinmemberMember 35573746-Oct-09 5:12 
GeneralRe: No dropdown icon PinmemberDavid Zenou7-Oct-09 8:20 
GeneralCode Updated PinmemberDavid Zenou2-Oct-09 0:10 
GeneralI can't update my code PinmemberDavid Zenou29-Sep-09 6:56 
GeneralRenderControl - Minor Bug PinmemberMember 73795629-Sep-09 0:14 
GeneralRe: RenderControl - Minor Bug PinmemberDavid Zenou29-Sep-09 4:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141220.1 | Last Updated 1 Oct 2009
Article Copyright 2009 by David Zenou
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid