Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you set the selected item in an ASP.NET dropdown via the display text?

Tags:

I have an ASP.NET dropdown that I've filled via databinding. I have the text that matches the display text for the listitem I want to be selected. I obviously can't use SelectedText (getter only) and I don't know the index, so I can't use SelectedIndex. I currently am selecting the item by iterating through the entire list, as show below:

ASP:

<asp:DropDownList ID="ddItems" runat="server" />  

Code:

ddItems.DataSource = myItemCollection; ddItems.DataTextField = "Name"; ddItems.DataValueField = "Id";  foreach (ListItem item in ddItems.Items) {     if (item.Text == textToSelect)     {         item.Selected = true;     } } 

Is there a way to do this without iterating through all the items?

like image 393
Ed Schwehm Avatar asked Aug 27 '10 19:08

Ed Schwehm


People also ask

How do I set the selected value in drop-down?

Using the jQuery change() method; you can set the selected value of dropdown in jquery by using id, name, class, and tag with selected html elements; see the following example for that: Example 1 :- Set selected value of dropdown in jquery by id.

How do you display the selected value of dropdown in a text box?

All you need to do is set the value of the input to the value of the select, in a select. onchange event handler. Show activity on this post. This is the brute force way to look up the currently selected option, check its value and use its display text to update your input.


2 Answers

You can try:

ddItems.Items.FindByText("Hello, World!").Selected = true; 

Or:

ddItems.SelectedValue = ddItems.Items.FindByText("Hello, World!").Value; 

Note that, if you are not certain that an items exists matching your display text, you may need to check the results of FindByText() for null.

Note that I use the first approach on a multiple-select list, such as a CheckBoxList to add an additional selection. I use the second approach to override all selections.

like image 62
kbrimington Avatar answered Oct 19 '22 15:10

kbrimington


Use the FindByText method of the ListItemCollection class, such as:

ListItem itemToSelect = ddlItems.Items.FindByText("some text to match");  if(itemToSelect != null) {     itemToSelect.Selected = true; } 
like image 28
KP. Avatar answered Oct 19 '22 13:10

KP.