Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 808
TGnat Avatar asked Nov 24 '08 22:11

TGnat


2 Answers

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;
like image 80
netadictos Avatar answered Nov 11 '22 05:11

netadictos


Anyone thought about:

foreach (ListItem li in drp.Items.Cast<ListItem>().Where(li => li.Value == ""))
{
    li.Selected = true;
}
like image 33
matt_lethargic Avatar answered Nov 11 '22 06:11

matt_lethargic