Sunday, July 27, 2008

Display Matched Item Value from ASP.NET Dropdown List

How do you display the dropdownlist item of an asp.net dropdown list according to some value you have as the match string? Let me demonstrate this via an example.

Create ListItems in an ASP.NET DropdownList

(I have used the dropdownlist name ddlTest for this example). Items are as follows:

asp.net

c#
vb.net


Traditional Loop Method

string value="asp.net";
for(int i=0; i
{
if(ddlTest.Items[i].Value==value)
{
ddlTest.Items[i].Selected=true;
}
}

You see it is inefficient. First it takes more lines of code. Second the loop increases as the item in the asp.net dropdownlist increases. The more efficient built in way is demonstrated below.

Display the Item Matched with Dynamic Input String

string value="asp.net";
ddlTest.electedValue = ddlTest.Items.FindByValue(value).Value;

The dropdownlist now displays the item having value equal to "asp.net". I have only put an example. The high dynamicity of this technique is seen when you supply some dynamic value to the varibale value used in the example above.


0 comments:

Post a Comment

Hope you liked this post. You can leave your message or you can put your valuable suggestions on this post here. Thanks for the sharing and cooperation!

Popular Posts

Recent Articles