Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SELECT a dropdown list item by value programmatically

How to SELECT a drop down list item by value programatically in C#.NET?

like image 708
David Bonnici Avatar asked Aug 08 '09 17:08

David Bonnici


People also ask

How do I select a dropdown by value?

A dropdown is represented by <select> tag and the options are represented by <option> tag. To select an option with its value we have to use the selectByValue method and pass the value attribute of the option that we want to select as a parameter to that method.

How can set the selected value of dropdown in asp net?

You can set the SelectedValue to the value you want to select. If you already have selected item then you should clear the selection otherwise you would get "Cannot have multiple items selected in a DropDownList" error. dropdownlist. ClearSelection(); dropdownlist.

Can multiple items be selected in a DropDownList?

Select Multiple Items From Drop Down List. Instead of limiting the drop down list to a single selection, you can use a bit of programming, combined with the data validation list, and allow multiple selections.

What is DropDownList in asp net?

The DropDownList control is a web server element that creates the drop-down menu and lets users select a single item from various options. You can add any number of items to the DropDownList. Almost all web pages contain a drop-down list, but it is mostly present in registration forms or sign-in pages.


1 Answers

If you know that the dropdownlist contains the value you're looking to select, use:

ddl.SelectedValue = "2"; 

If you're not sure if the value exists, use (or you'll get a null reference exception):

ListItem selectedListItem = ddl.Items.FindByValue("2");  if (selectedListItem != null) {     selectedListItem.Selected = true; } 
like image 190
ScottE Avatar answered Sep 20 '22 15:09

ScottE