5

I need to create a dropdownlist where in the user can select a value from the dropdownlist or type the value in.

Exactly like the "Where do you come from ? " dropdown in the below link :

http://www.dhtmlgoodies.com/scripts/form_widget_editable_select/form_widget_editable_select.html

I know it is a common question and there are similar queries on stack overflow as well but I couldn't find a simple working solution.

I have referred the following links :

http://www.codeproject.com/Articles/8578/Editable-Dropdown-DHTML-Behavior http://www.codeproject.com/Articles/290218/Custom-ASP-NET-Editable-DropDownList http://codeverge.com/asp.net.web-forms/editable-dropdown-list-c/392261

Has anyone worked on this before and give me an idea as to how I can proceed ?

Richard Ev
  • 52,939
  • 59
  • 191
  • 278
user1698232
  • 183
  • 2
  • 5
  • 20
  • 1
    a ComboBox is what you want, typically a WebForms control but there is one in the AjaxControlToolkit: http://www.asp.net/web-forms/overview/ajax-control-toolkit/combobox/how-do-i-use-the-combobox-control-cs – Hugo Yates Mar 16 '15 at 11:52
  • @Hugo- I'll look into that and let you know ! – user1698232 Mar 16 '15 at 13:37
  • I recommend Select2, available here: https://select2.github.io/ – Family Mar 16 '15 at 14:18
  • @Hugo - I tried following the article but I guess comboBox cannot be used in Web Forms.Apparently,it is only for Windows Forms Application if I am not mistaken.Do correct me if I am wrong ! – user1698232 Mar 17 '15 at 06:24
  • 1
    They're really not the easiest things in WebForms but that link is for using it on a WebForm. You need the `AjaxControlToolkit` which you can get as a NuGet package. – Hugo Yates Mar 17 '15 at 09:25
  • @Hugo- I tried that but : refer this http://stackoverflow.com/questions/29092749/ajax-combobox-not-working – user1698232 Mar 17 '15 at 09:27

3 Answers3

2

Another solution is as follows
You could use the Ajax Control Toolkit Nuget

Step 1: Add the Ajax Control Toolkit from the Nuget Packages in your references

Step 2: If you do not get the Ajax Control Toolkit controls into your Toolbox, you need to create a separate Tab and name it Ajax Toolkit Controls.
Then right click on it and select choose items.
Browse to location where the Ajax Control Toolkit's dll is located, select it.
You will see set of controls getting populated into the window.
Select Ok, this will result into populating the tab with the Ajax Control Toolkit Controls.

Step 3: Since Ajax Toolkit Controls are an extra add-on package, you need to register them as a part of the page using them.If installed as a nuget, this step can be neglected.

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit" %>

Note: The tagprefix should match the tagprefix used by you in your program for the AjaxControlToolkit Controls.

Step 4: Add the ScriptManager Control, It is required for providing support for client-side AJAX features. As a result it loads and registers the Microsoft AJAX library to enable the features.

<asp:ScriptManager ID="ScriptManager1" runat="server" />

Step 5: Proceed by adding the ComboBox from the toolbox and configure it by linking it to your database using the SQLDataSource

The complete source code is as follows

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxComboboxSample.aspx.cs" Inherits="StacksEmptied.AjaxComboboxSample" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <style type="text/css">
        #ComboBox1_ComboBox1_OptionList {
            width: 10% !important;
        }
    </style>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <ajaxToolkit:ComboBox ID="ComboBox1" AppendDataBoundItems="True" runat="server" AutoCompleteMode="Suggest" DataSourceID="SqlDataSource1" DataTextField="Fruits" DataValueField="Fruits" MaxLength="0" Style="display: inline;">
            </ajaxToolkit:ComboBox>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:FruitsConnectionString %>" SelectCommand="SELECT * FROM [Fruits]"></asp:SqlDataSource>
        </div>
    </form>
</body>
</html>

I have tested this code on all the below settings Testing Environment:
Chrome Browser Version 43.0.2334.0 dev-m (64-bit)
Internet Explorer 11
Firefox 36.0.1
Visual Studio 2013 edition

Shadab K
  • 1,677
  • 1
  • 16
  • 25
  • It gives me an error : Error 5 The type or namespace name 'ComboBox' does not exist in the namespace 'AjaxControlToolkit' (are you missing an assembly reference?) – user1698232 Mar 26 '15 at 04:11
  • Have you included AjaxControlToolkit in your references? If not try once more installing the entire AjaxControlToolkit that comes along with other tools and packages in the Nuget market. – Shadab K Mar 29 '15 at 11:39
0

You can try using JqueryUI Autocomplete Combobox.
It will let you type in text as well as select the item of your choice from a dropdown.
As an extra feature it lets you use the autocomplete feature to get a enhance UI experience.

I am attaching a demo which is coupled with bootstrap 3.3.4

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
  <title></title>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
  <link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />

  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <link href="https://jqueryui.com/resources/demos/style.css" rel="stylesheet" />
  <style>
    .custom-combobox {
      position: relative;
      display: inline-block;
    }
    .custom-combobox-toggle {
      position: absolute;
      top: 0;
      bottom: 0;
      margin-left: -1px;
      padding: 0;
    }
    .custom-combobox-input {
      margin: 0;
      padding: 5px 10px;
    }
    .ui-state-default,
    .ui-widget-content .ui-state-default,
    .ui-widget-header .ui-state-default {
      border: 1px solid #421D1D;
      background: #ffffff url("images/ui-bg_glass_75_e6e6e6_1x400.png") 50% 50% repeat-x !important;
      font-weight: normal;
      color: #555555;
    }
    /* Corner radius */
    .ui-corner-all,
    .ui-corner-top,
    .ui-corner-left,
    .ui-corner-tl {
      border-top-left-radius: 0px !important;
    }
    .ui-corner-all,
    .ui-corner-top,
    .ui-corner-right,
    .ui-corner-tr {
      border-top-right-radius: 0px !important;
    }
    .ui-corner-all,
    .ui-corner-bottom,
    .ui-corner-left,
    .ui-corner-bl {
      border-bottom-left-radius: 0px !important;
    }
    .ui-corner-all,
    .ui-corner-bottom,
    .ui-corner-right,
    .ui-corner-br {
      border-bottom-right-radius: 0px !important;
    }
  </style>
  <script>
    (function($) {
      $.widget("custom.combobox", {
        _create: function() {
          this.wrapper = $("<span>")
            .addClass("custom-combobox")
            .insertAfter(this.element);

          this.element.hide();
          this._createAutocomplete();
          this._createShowAllButton();
        },

        _createAutocomplete: function() {
          var selected = this.element.children(":selected"),
            value = selected.val() ? selected.text() : "";

          this.input = $("<input>")
            .appendTo(this.wrapper)
            .val(value)
            .attr("title", "")
            .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
            .autocomplete({
              delay: 0,
              minLength: 0,
              source: $.proxy(this, "_source")
            })
            .tooltip({
              tooltipClass: "ui-state-highlight"
            });

          this._on(this.input, {
            autocompleteselect: function(event, ui) {
              ui.item.option.selected = true;
              this._trigger("select", event, {
                item: ui.item.option
              });
            },

            autocompletechange: "_removeIfInvalid"
          });
        },

        _createShowAllButton: function() {
          var input = this.input,
            wasOpen = false;

          $("<a>")
            .attr("tabIndex", -1)
            .attr("title", "Show All Items")
            .tooltip()
            .appendTo(this.wrapper)
            .button({
              icons: {
                primary: "ui-icon-triangle-1-s"

              },
              text: false
            })
            .removeClass("ui-corner-all")
            .addClass("custom-combobox-toggle ui-corner-right")
            .mousedown(function() {
              wasOpen = input.autocomplete("widget").is(":visible");
            })
            .click(function() {
              input.focus();

              // Close if already visible
              if (wasOpen) {
                return;
              }

              // Pass empty string as value to search for, displaying all results
              input.autocomplete("search", "");
            });
        },

        _source: function(request, response) {
          var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
          response(this.element.children("option").map(function() {
            var text = $(this).text();
            if (this.value && (!request.term || matcher.test(text)))
              return {
                label: text,
                value: text,
                option: this
              };
          }));
        },

        _removeIfInvalid: function(event, ui) {

          // Selected an item, nothing to do
          if (ui.item) {
            return;
          }

          // Search for a match (case-insensitive)
          var value = this.input.val(),
            valueLowerCase = value.toLowerCase(),
            valid = false;
          this.element.children("option").each(function() {
            if ($(this).text().toLowerCase() === valueLowerCase) {
              this.selected = valid = true;
              return false;
            }
          });

          // Found a match, nothing to do
          if (valid) {
            return;
          }

          // Remove invalid value
          this.input
            .val("")
            .attr("title", value + " didn't match any item")
            .tooltip("open");
          this.element.val("");
          this._delay(function() {
            this.input.tooltip("close").attr("title", "");
          }, 2500);
          this.input.autocomplete("instance").term = "";
        },

        _destroy: function() {
          this.wrapper.remove();
          this.element.show();
        }
      });
    })(jQuery);

    $(function() {
      $("#combobox").combobox();
      $("#toggle").click(function() {
        $("#combobox").toggle();
      });
    });
  </script>
</head>

<body>
  <form id="form1" runat="server">
    <div>
      <div class="ui-widget">
        <select id="combobox" class="form-control">
          <option value="">Select your option</option>
          <option value="Apple">Apple</option>
          <option value="Banana">Banana</option>
          <option value="Cherry">Cherry</option>
          <option value="Date">Date</option>
          <option value="Fig">Fig</option>
          <option value="Grape">Grape</option>
          <option value="Kiwi">Kiwi</option>
          <option value="Mango">Mango</option>
          <option value="Orange">Orange</option>
          <option value="Pumpkin">Pumpkin</option>
          <option value="Strawberry">Strawberry</option>
          <option value="Tomato">Tomato</option>
          <option value="Watermelon">Watermelon</option>
        </select>
      </div>

    </div>
  </form>
</body>

</html>
I have tested this code on all the below settings Testing Environment:
Chrome Browser Version 43.0.2334.0 dev-m (64-bit)
Internet Explorer 11
Firefox 36.0.1
Visual Studio 2013 edition

Hope this solves your issue.

Shadab K
  • 1,677
  • 1
  • 16
  • 25
0

This JQuery plugin will solve your problem, it turns DropDown lists into auto-complete like fields, even though it changes the HTML structure of the select element ASP.NET is still able to detect which option was selected.

Source: https://github.com/indrimuska/jquery-editable-select

OBS: To persist data to postback you need to bind the events associated with postback with JavaScript, make the "Combo Box" a dropdownlist again (with the persisted value).

Sample Usage:

$('#editable-select').editableSelect();
<link href="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet">
<select id="editable-select">
    <option>Alfa Romeo</option>
    <option>Audi</option>
    <option>BMW</option>
    <option>Citroen</option>
</select>
<script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>
ArthurG
  • 335
  • 2
  • 11