TGnat TGnat - 11 months ago 86
ASP.NET (C#) Question

Select a ListItem from DropDownList using a Linq Query

I' trying to use a Linq query to find and set the selected value in a drop down list control.

Dim qry = From i In ddlOutcome.Items _
Where i.Text.Contains(value)

Dim selectedItem As ListItem = qry.First

ddlOutcome.SelectedValue = selectedItem.Value

Even though the documentation says that the DropDownList.Items collection implements IEnumerable I get an error in the Where clause that Option Strict ON disallows late binding!

Answer Source

Thank you for the suggestions, they were both helpful in leading me to a workable solution. While I agree that using the methods of the drop list itself should be the way to go, I don't have an exact match on the text of the items in the list so I needed another way.

    Dim qry = From i In ddlOutcome.Items.Cast(Of ListItem)() _
              Where i.Text.Contains(value)

    qry.First().Selected = True

The linq query seems preferable to iterating through the list myself, and I learned something in the process.