views:

3345

answers:

4

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!

+1  A: 

My vb.net is shaky, (c# guy) but try:

Dim qry = From DirectCast(i, ListItem) In ddlOutcome.Items ...

I may have the DirectCast syntax wrong, but you know where I'm coming from. The problem is that at compile time, Items is not verifiable as as a collection of ListItem because IEnumerable's Current property returns Object. Items is not a generic collection.

-Oisin

x0n
+1  A: 

I can give you an answer in C#, and i hope it helps you.

The easiest way it to use the methods of DropDownlist, better than linq query:

DropDownList1.SelectedIndex = 
       DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("2"));

If you want the linq query it would be like this:

var selected=from i in DropDownList1.Items.Cast<ListItem>()
                     where ((ListItem)i).Text.Contains("2") select i;

DropDownList1.SelectedValue = selected.ToList()[0].Text;
netadictos
A: 

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.

TGnat
A: 

simple way to select using following code

foreach (ListItem i in DropDownList1.Items) { DropDownList1.SelectedValue = i.Value; if (DropDownList1.SelectedItem.Text=="text of your DropDownList") {break;} }