Search an ASP.NET DropDownList

A user mailed me recently asking me the simplest way to search an ASP.NET DropDownList. I think the simplest way is using the foreach loop as shown below (although it may be slow when the items are huge):

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title></title>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:DropDownList ID="DropDownList1" runat="server">
<
asp:ListItem Text="Item1"></asp:ListItem>
<
asp:ListItem Text="Item2"></asp:ListItem>
<
asp:ListItem Text="Item3"></asp:ListItem>
</
asp:DropDownList>
<
br />
<
asp:Button ID="btnSearch" runat="server" Text="Search"
onclick="btnSearch_Click"/>
</
div>
</
form>
</
body>
</
html>

C#

protected void btnSearch_Click(object sender, EventArgs e)
{
string str = "Item2";
// Using For Each
foreach (ListItem li in DropDownList1.Items)
{
if (li.Value == str)
{
this.DropDownList1.SelectedValue = li.Value.ToLower();

}
}
}

VB.NET

Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim str As String = "Item2"
' Using For Each
For Each li As ListItem In DropDownList1.Items
If li.Value = str Then
Me
.DropDownList1.SelectedValue = li.Value.ToLower()

End If
Next
li
End Sub
The code shown above loops through all the items of a DropDownList and selects the item if the string is found. To make the code case insensitive, use ToLower()/ToUpper() and compare the values.

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: