Friday, June 5, 2009

Searching a ListBox or DropDownList using the ListSearchExtender Control using ASP.NET AJAX

The ListSearchExtender control is a control that ships with the Microsoft AJAX Control Toolkit. ListSearchExtender enables the DropDownList and ListBox to be searchable. The user can navigate to and select an item in the list by simply typing the first few characters. This could be especially useful if there is a long list to be searched.
Let us quickly see how to use the ListSearchExtender control in our projects.
Step 1: Add a ListBox and DropDownList to the webform.
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
Click on the
ListBox and type the word to search<br />
<br />
<br />
<asp:ListBox ID="ListBox1" runat="server">asp:ListBox>
<br />
<br />
<br />
Click on the
DropDownList and type the word to search<br />
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server">
asp:DropDownList>
<br />
div>
form>
body>
Step 2: Populate the ListBox and DropDownList with a few items. Over here, we are using the ‘for’ loop to add items to the ListBox and DropDownList. If you want, you can implement a real world scenario where you can connect to a database and bind the controls to a collection.
C#
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i <>
{
ListBox1.Items.Add("Items " + i.ToString());
DropDownList1.Items.Add("Items " + i.ToString());
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
For i As Integer = 0 To 99
ListBox1.Items.Add("Items " & i.ToString())
DropDownList1.Items.Add("Items " & i.ToString())
Next i
End Sub
Step 3: Drag and drop two ’ ListSearchExtender’ controls to the form. If you have the AJAX Control Toolkit, you will find the ListSearchExtender control in the ‘Ajax Toolkit’ tab of the toolbox. Set the ‘TargetControlID’ of ListSearchExtender1 as ‘ListBox1’ and ‘TargetControlID’ of ListSearchExtender2 as ‘DropDownList1’ as shown below:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
Click on the
ListBox and type the word to search<br />
<br />
<br />
<asp:ListBox ID="ListBox1" runat="server">asp:ListBox>
<br />
<cc1:ListSearchExtender ID="ListSearchExtender1" runat="server" TargetControlID="ListBox1">
cc1:ListSearchExtender>
<br />
<br />
Click on the
DropDownList and type the word to search<br />
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server">
asp:DropDownList>
<cc1:ListSearchExtender ID="ListSearchExtender2" runat="server" TargetControlID="DropDownList1">
cc1:ListSearchExtender>
<br />
div>
form>
body>
Run the application and click on the ListBox control. Search for an item (Eg: “Items 45”). You will observe that the ListSearchExtender searches the item and highlights it for us. Similarly try it out for the dropdownlist control too.

No comments:

Popular Posts