CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Home > CodeDigest >  
Technologies
 


Make DropDownList Item Selection in Runtime in ASP.Net
Submitted By Satheesh Babu B
On 10/19/2008 7:47:38 AM
Tags: asp.net,CodeDigest  

 

Sometimes we will have requirements to select a dropdownlist value dynamically. For example, in an edit item page we normally populate the existing user inputs so that he can change the existing values. In these forms, if we have DropDownlist control we need to select the item which the user has saved already when it is presented in editable view.

 

We can do this simple task very easily instead of iterating through the items to make the selection.

 

Selecting a Item by Text

DropDownList1.Items.FindByText("valuetoselect").Selected = true;

 

Selecting a Item by Value

DropDownList1.Items.FindByValue("valuetoselect ").Selected = true;

 

Sometimes, when you do this you may encounter this error!

 

Cannot have multiple items selected in a DropDownList.

 

You can overcome this error by setting the previous selection to false.

 

DropDownList1.SelectedItem.Selected = false;

 

Just copy the above line before the actual code that makes the runtime selection. This code actually clears any previous selections which will give the above error!

 

You can also use the following code to prevent the error!

 

DropDownList1.SelectedIndex = -1;

Recent Codes
  • View All Codes..