July 18, 2009

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.

'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Search an ASP.NET DropDownList"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions