views:

33

answers:

2

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?

+6  A: 

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.

kbrimington
you beat me to it. I use the first option.
rockinthesixstring
the null reference check should be used on either of those options. You can't guarantee the text will be there.
KP
@rock: Thanks for your response. I added a note explaining when I would choose one over the other.
kbrimington
@KP: Thanks. I had made mention of that already, but left it out for clarity. Besides, there exist cases where you can guarantee text exists and save a few lines of code.
kbrimington
Thanks! Quick answer and effective.
Ed Schwehm
@kbrimington: fair enough. + 1!
KP
+1  A: 

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;
}
KP