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

Viewed 48583

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?

4 Answers

If you have to select dropdown selected item text for multiple dropdown cases then use this way.

// Call Method
SelectDropdownItemByText(ddlDropdown.Items.FindByText("test"));

// Define method
public void SelectDropdownItemByText(ListItem item)
{
    if (item != null)
    {
        item.Selected = true;
    }
}
Related