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.




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: