This is my personal blog. The views expressed on these pages are mine alone and not those of my employer.

Friday, 15 May 2009

How to create a ComboBox in ASP.NET

The .NET framework has long been deficient in the fact it DOES NOT include a ComboBox control as standard.  For those of you who do not know what a ComboBox is, it is essentially an editable drop down list (see here) which allows the user to either type OR select from a list.  I suppose it is rather analogous to the browsers address bar.

There are other options out there to provide this functionality (such as the AJAX solution above) and countless paid for controls, but what if all you want is a simple, no frills ComboBox?

Well it is actually rather simple to create one.

What is required is to add a TextBox and a Button (or if you're feeling fancy an image) and a ListBox below them, so that you have something like:

    <asp:TextBox ID="TextBox1" runat="server"
        style="z-index: 1; left: 102px; top: 28px; position: absolute"
    <input id="Button1" type="button" value="V" style="width:20px; height:28px; z-index: 1; left: 239px; top: 27px; position: absolute" onclick="toggle_visibility('div1')" />
    <div id="div1" style="display:none">
        <asp:ListBox ID="ListBox1" runat="server"
            style="z-index: 1; left: 102px; top: 59px; position: absolute"
            Width="155px" AutoPostBack="True">
            <asp:ListItem Selected="True">Sids Co</asp:ListItem>
            <asp:ListItem>Jacks Co</asp:ListItem>
            <asp:ListItem>Daves Co</asp:ListItem>

Then all is required is a spot of JavaScript to show/hide the ListBox when you click the button:

  function toggle_visibility(id) {
       var e = document.getElementById(id);    
       if( == 'block')
 = 'none';
 = 'block';

Of course you may find that you'll have to play around with CSS to get it looking correctly and a bit of codebehind so that when the user selects from the ListBox the TextBox is updated correctly.  However what you have is essentially a working ComboBox that works in all browsers, and to be honest, what else do you need?

Those looking for a more elegant solution are either going to have to cough up and pay for the control, or move towards the AJAX solution (which will NOT work with JavaScript disabled).  Blame Microsoft :-)

EDIT:  I have found a nice free version of a ComboBox control .  However I would use with caution as it doesn't seem to work in FireFox :-S


  1. suppose if we enter listitem value Sids Co .

    first letter it should automatically select the whole string in textbox as it happens in it possible

    1. Why don't you download it to make this change? You could then share it with the community by posting a link here.