views:

55

answers:

5

I'm using a DropDownList with a data source which successfully populates the list. However, I want one of the items to be selected, namely the one where the value matches the path and query of the current request.

ddlTopics.DataSource = pdc;
ddlTopics.DataBind();
foreach (ListItem item in ddlTopics.Items)
{
    item.Selected = item.Value.Equals(this.Page.Request.Url.PathAndQuery);
}

Using the debugger in Visual Studio 2008 reveals that item.Selected becomes true exactly once in the loop, but the rendered select has no option that is selected.

Any ideas?

A: 

Set theddlTopics.SelectedIndex property to the index of the item you wanted selected.

Matt Dearing
A: 

I've always used

ddlTopics.SelectedIndex

to indicate that a row is selected, rather than assigning to the row individually.

Dave
A: 

This is how I do it...

  foreach (var itm in cboOffice.Items) {
        if (itm.Value == Session("office")) {
            itm.Selected = true;
            break; //OR EXIT FOR
        }
    }
Albert
+2  A: 

You can try this:

ddlTopics.SelectedIndex = ddlTopics.Items.IndexOf(ddlTopics.Items.FindByValue(this.Page.Request.Url.PathAndQuery));
Kristof Claes
Very, very neat. Thank you! EDIT: Saw that Sorpigal had an even more superior solution, so I accepted her/his instead.
Deniz Dogan
This is essentially what setting .SelectedValue does, except that .SelectedValue does more error checking.
Sorpigal
The main reason I use SelectedIndex is because SelectedValue throws an ArgumentOutOfRange exception when the value is not found. SelectedIndex does nothing when the index is not found.
Kristof Claes
More precisely SelectedIndex will call ClearSelection() when the index is not found. I consider throwing an exception to be better (I'd rather handle an exception than have non-obvious behavior) but it depends on your personal preference.
Sorpigal
+2  A: 

Use

ddlTopics.SelectedValue = this.Page.Request.Url.PathAndQuery;

    // Summary:
    //     Gets the value of the selected item in the list control, or selects the item
    //     in the list control that contains the specified value.
Sorpigal