Select ListItem from DropDownList using Linq query

I am trying to use the Linq query to search and set the selected value in a drop down list.

Dim qry = From i In ddlOutcome.Items _ Where i.Text.Contains(value) Dim selectedItem As ListItem = qry.First ddlOutcome.SelectedValue = selectedItem.Value 

Although the documentation says that the DropDownList.Items collection implements IEnumerable, I get an error in the Where clause, which Option Strict ON prohibits late binding!

+4
source share
5 answers

Thank you for the suggestions, and they were useful in order to lead me to a workable solution. Although I agree that using the methods of the drag list itself should be a way, I do not have an exact match with the text of the items in the list, so I need a different 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 for repeating the list itself, and I learned something in the process.

+2
source

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

The easiest way to use DropDownlist methods is better than linq query:

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

If you want the linq query to 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; 
+8
source

Someone thought:

 foreach (ListItem li in drp.Items.Cast<ListItem>().Where(li => li.Value == "")) { li.Selected = true; } 
+5
source

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

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

I may have DirectCast syntax, but you know where I come from. The problem is that at compile time, items are not checked as a ListItem collection, since the IEnumerable Current property returns Object. Elements are not a common collection.

-Oisin

+1
source

easy way to select with the following code

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

All Articles