CodeSnip: How to Create a Dynamic Searchable DropDown List in ASP.NET
 
Published: 04 Oct 2006
Abstract
In this article Nidal examines how to create a dynamic searchable dropdown list using ASP.NET.
by Nidal Arabi
Feedback
Average Rating: 
Views (Total / Last 10 Days): 43234/ 121

Problem

I have come across many situations where I found myself in need of providing the end user with a searchable combo box that returns the selected value to a text box.  An example of such a case is giving the end user the ability to select the name of a product from a long list.  ASP.NET does not provide the ability as a default control.  So, what I am going to do?

Suggested Design

One idea is to create your own control.  Note, I have seen some solutions on the web, however none of them satisfied my requirements.  Therefore, I took one and updated it to suit my needs.  I created a new popup window that takes the given parameters as to what to fill the box, as well as, the return control.

Solution

Obviously, you are eager to open your Visual Studio .NET 2003 and start coding.  So let us do it.

1.      Open Visual Studio .NET 2003, create a new ASP.NET website and give it a name: EDropDown.

2.      In the default form created, insert two labels and two HTML input boxes.

3.      Give the first label a text property My Product Name and the second one a text property My Employee Name.

4.      As for the two input boxes, put the ID property type TxtProductName and TxtEmployeeName in sequence.

By now we should have Figure 1 on the first form, the default start up design.

Figure 1

5.      Now, we move to the Drop Down list WebForm in order to build it.  In the solution explorer window, right click the solution name and choose Add New Item then choose a web form and save the file as NamePicker.aspx.

Figure 2


6.      It is a good idea to start with the picture to display the form design. Take a look at Figure 2.

7.      As you can see, you should start with a label that displays a title for the page Name Picker.

8.      Create another label with a text property Search Name.

Create an HTML input box in front of it with an ID property TxtOldName.

9.      Create a drop down box called CbxName.

10.  Create an html button called Button1 and a value Select Name.

At the end, create an HTML input box with an ID property TxtNewName with type Hidden.

Now for the behind the scene work, we have to insert the following JavaScript inside the head tag of the HTML view of the form.

Listing 1

<script language = "JavaScript"> 
function FindText(finder_textbox, finder_selectbox)
{
  var searchstr = finder_textbox.value;
  var myexp = new RegExp(("^" + searchstr), "i");
  var foundresult = false;
  var i = 0;
  while ((foundresult = false) || (i < finder_selectbox.length))
  {
    if (myexp.test(finder_selectbox.options[i].text))
    {
      finder_selectbox.options[i].selected = true foundresult = true;
      document.Form1.TxtNewName.value = finder_selectbox.options[i].text;
      i = 32768;
    }
    i++;
  }
}
 
function FindText1(finder_textbox, finder_selectbox)
{
  var searchstr = finder_textbox.value;
  var myexp = new RegExp(("^" + searchstr), "i");
  var foundresult = false;
  var i = 0;
  while ((foundresult = false) || (i < finder_selectbox.length))
  {
    if (myexp.test(finder_selectbox.options[i].text))
    {
      finder_selectbox.options[i].selected = true foundresult = true;
      document.Form1.TxtNewName.value = finder_selectbox.options[i].text;
      i = 32768;
      window.close();
    }
    i++;
  }
}
 
function Done()
{
  var par1 = "par1";
  var par2 = "par2";
  var par3 = "par2";
  var par4 = "par2";
  par1 = document.Form1.TxtNewName.value;
  par2 = document.Form1.TxtNewName.value;
  par3 = document.Form1.TxtNewName.value;
  par4 = document.Form1.TxtNewName.value;
  var MyArgs = new Array(par1, par2, par3, par4);
  window.returnValue = MyArgs;
  window.close();
}
 
function doInit()
{
  var par1 = "Apar";
  var par2 = "par2";
  var par3 = "par3";
  var par4 = "par4";
  var MyArgs = new Array(par2, par3, par4);
  MyArgs = window.dialogArguments;
  document.Form1.TxtOldName.value = MyArgs[1].toString();
  document.Form1.TxtPattern.Text = document.Form1.TxtPattern.Text + ' : ' +
    MyArgs[0].toString();
}
 
function SetValue(finder_selectbox)
{
  var foundresult = false;
  var i = 0;
  document.Form1.TxtNewName.value = finder_selectbox.value;
  document.Form1.TxtOldName.value = finder_selectbox.value;
}
 
function CheckEnter()
{
  if (event.keyCode == 13)
    Done();
}
</script>

11.  Another addition is to the body tag of the form in order to allow it to set focus and return the name on exit.

Listing 2

<body onblur="this.window.focus();" bgColor="#ffff66" 
onload="doInit()" ms_positioning="FlowLayout" onunload="Done();">

12.  When the user presses any key in the search box, the dropdown box should select the nearest match to it.  This is done by inserting the following HTML code.

13.  A change to Select Name is also needed as follows.

Listing 3

<BUTTON id="BUTTON1" onmousedown="SetValue(CbxName);" 
onclick="Done();" type="button" runat="server">

14.  You can now close the HTML view and return to the design view.

15.  In the Page load event of the form insert the following code.

Listing 4

If Not Me.IsPostBack Then
  Call SetupData()
End If

16.  The setup data procedure is the key to our dropdown box.

Listing 5

Public Sub SetupData()
  Dim MySQLConnection As New SqlClient.SqlConnection
  Dim MySQLCommand As New SqlClient.SqlCommand
  Dim MyDataAdapter As New SqlClient.SqlDataAdapter
  Dim MyDataSet As New Data.DataSet
  Dim ESQL As String
  ESQL = Request.QueryString().Get("ESQL")
  ESQL = ESQL.Replace("char(43)", "+")
  MySQLConnection.ConnectionString = 
"Data Source=.; Initial Catalog=Northwind; User ID=sa; Password=pass@word1"
  MySQLConnection.Open()
  MySQLCommand.Connection = MySQLConnection
  MySQLCommand.CommandType = CommandType.Text
  MySQLCommand.CommandText = ESQL
  MyDataAdapter.SelectCommand = MySQLCommand
  MyDataAdapter.Fill(MyDataSet, "ComboBoxTable")
  CbxName.DataSource = MyDataSet
  CbxName.DataMember = "ComboBoxTable"
  CbxName.DataValueField = MyDataSet.Tables.Item("ComboBoxTable").Columns(0).ColumnName
  CbxName.DataTextField = MyDataSet.Tables.Item("ComboBoxTable").Columns(1).ColumnName
  CbxName.DataBind()
  CbxName.SelectedIndex = 0
  TxtNewName.Value = CbxName.SelectedValue
  MySQLConnection.Close()
End Sub

Now we turn back to our webform1 and add the following for the two input boxes and for the employee input box.

Listing 6

<INPUT onkeypress="if (event.keyCode == 13)
 this.value=NamePicker('Select ProductID, ProductName From Products',this.value,this.value);"
 ondblclick="this.value=NamePicker('Select ProductID, ProductName 
From Products',this.value,this.value);"
 id="TxtProductName"
 type="text" name="TxtProductName"
 runat="server"></P>

Listing 7

<INPUT onkeypress="if (event.keyCode == 13)
 this.value=NamePicker('Select EmployeeID, FirstName + char(32) + LastName 
From Employees',this.value,this.value);"
 ondblclick="this.value=NamePicker('Select EmployeeID, FirstName char(43)
 char(32) char(43) LastName From Employees',this.value,this.value);"
 id="TxtEmployeeName" type="text" name="TxtEmployeeName"
 runat="server">

17.  Since our input boxes are calling a JavaScript function, we need to provide the code for it in the header section of the HTML.

Listing 8

<script language = "javascript" type = "text/javascript" > function
   TrimString(sInString)
{
  sInString = sInString.replace( /  ^  \
    s +  / g, ""); // strip leading
  return sInString.replace( /  \
    s + $ / g, ""); // strip trailing
}
 
function NamePicker(StrSQL, StrOldName, StrNewName)
{
  StrOldName = TrimString(StrOldName);
  StrNewName = TrimString(StrNewName);
  var MyArgs = new Array(StrSQL, StrOldName, StrNewName);
  var WinSettings =
    "center:yes;resizable:no;dialogHeight:300px;dialogWidth:350px";
  var MyArgs = window.showModalDialog("NamePicker.aspx?ESQL=" + StrSQL, MyArgs,
    WinSettings);
  if (MyArgs != null)
  {
    return MyArgs[0].toString();
  }
}
</script>

Congratulations, you have created your popup searchable dropdown box that satisfies your needs.

Tips

This section aims at providing some explanations about some workarounds used in code in order to provide flexibility.

·         To provide the ability to concatenate strings, such as in the employee name, char(43) was used and replaced by a "+" when receiving the query string to prevent IE from replacing it by a space.

·         Another tip is the java function that trims the text box content before it is sent to the combo filter to allow for maximum search capability.

·         Another Tip is using the Char(32) to provide the space option when concatenating.

·         This allows the user to fill the combo box only when needed, not with the original page in order to minimize the page size.

Downloads

Conclusion

Providing the user a common windows option makes the web interface more enjoyable.  Also, the programmers using the code provided in this article have greater flexibility in customizing the application than before.  I hope that you liked this article and could use it.



User Comments

Title: jQuery Searchable DropDown Plugin   
Name: Haggi
Date: 2009-12-01 6:58:48 PM
Comment:
Have a lookt at this plugin

http://plugins.jquery.com/project/searchabledropdown
Title: javascript   
Name: lalita
Date: 2009-03-30 5:53:17 PM
Comment:
hi, i found your article very useful but how can i get information on dropdownlist which use javascript
Title: How to create a drop down list in a form view in VB 2005 (ASP.NET)   
Name: Joseph Tran
Date: 2008-11-17 11:09:20 AM
Comment:
Dear Mr. Hitashi,
How are you doing? My name Joe, and I'm new to ASP.NET 2.0 (In VB). I wish to ask you a question about how to create a drop down list in Form View. So the user can select their picks without making any mistakes or mistypo. Would you please show me how or tell me how to create it step by step?

Thank You Very Much
Joe

my email is FBI1971US@yahoo.com
Title: Prob with autopostback   
Name: Hitashi
Date: 2008-09-16 4:43:03 AM
Comment:
Hi can you plz help me to resolve this prob. I m creating no of dynamic dropdown list. It works fine upto 2 dropdownlist. But if the 3rd one come the second one hides from the form due to autopostback can you help me plz to resolve this prob

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2021 ASPAlliance.com  |  Page Processed at 2021-12-07 7:53:35 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search