DropDownList Selection as you type in


Introduction:

The ASP.NET DropDownList server control allows positioning within the list by typing the first character. This method does not require a trip to the server.

In this article we'll see how to type in the DropDownList. To test the working we'll place a textbox besides the dropdownlist. We'll type as many characters in the dropdownlist that we want to match in the list and check if they appear in the textbox.

The screen would be with following controls

  • DropdownList 
  • HTML TextBox 
  • Button
  • Label

Screenshot



Code for User Interface goes as follows:

<asp:DropDownList id="DropDownList1" onKeyup="TrapKey(this, this.event)" runat="server"></asp:DropDownList>
<
asp:Button id="Button1" runat="server" Text="Show"></asp:Button>
<
input type="text" disabled name="result" value="test" size="20" ID="Text1">
<
br><asp:Label id="Label4" runat="server" Font-Names="Georgia"></asp:Label>
</
asp:Label>

The Javascript that would allow to type in the dropdown as the user types goes below:

<script language="JavaScript" type="text/javascript">
function
clearWord()
{
userWord = "";
document.forms[0].result.value = "";
}
var userWord = "";
function TrapKey(obj, e)
{
thekey = String.fromCharCode(
event.keyCode);
userWord += thekey;
for (var i = 0; i < obj.options.length; i++) {
var txt = obj.options[i].text.toUpperCase();
document.forms[0].result.value = userWord;
if (txt.indexOf(userWord) == 0) {
obj.options[i].selected =
true;
obj.options[i].focus();
break;
}
}
setTimeout("clearWord()", 3000)
}
</script>

In code behind

C#

SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds;
String strConn;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!Page.IsPostBack)
{
try
{
strConn="server=localhost;database=northwind;uid=sa;pwd=;";
mycn =
new SqlConnection(strConn);
myda =
new SqlDataAdapter("select * from Employees", mycn);
ds=
new DataSet ();
myda.Fill (ds,"Table");
DropDownList1.DataSource =ds.Tables [0];
DropDownList1.DataTextField =ds.Tables[0].Columns
"FirstName"].ColumnName.ToString() ;
DropDownList1.DataValueField = ds.Tables[0].Columns
"EmployeeId"].ColumnName.ToString();
DropDownList1.DataBind();
}
catch(Exception ex)
{
Response.Write (ex.Message );
}
}
}
private void Button1_Click(object sender, System.EventArgs e)
{
Label1.Text="You have selected " + DropDownList1.SelectedItem.Text;
}


The final Output


Similar Articles