5

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!

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
TGnat
  • 3,903
  • 8
  • 35
  • 46

5 Answers5

9

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;
p.campbell
  • 98,673
  • 67
  • 256
  • 322
netadictos
  • 7,602
  • 2
  • 42
  • 69
6

Anyone thought about:

foreach (ListItem li in drp.Items.Cast<ListItem>().Where(li => li.Value == ""))
{
    li.Selected = true;
}
matt_lethargic
  • 2,706
  • 1
  • 18
  • 33
2

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
  • 3,903
  • 8
  • 35
  • 46
  • I have reason to use FirstOrDefault in these situations to avoid downstream issues. Check for null! – Allen Oct 31 '15 at 10:43
  • another answer for reference , it seems `Selected` is same meaning as `Checked` https://stackoverflow.com/questions/18924147/how-to-get-values-of-selected-items-in-checkboxlist-with-foreach-in-asp-net-c – yu yang Jian Jun 13 '17 at 15:52
1

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
  • 51,312
  • 7
  • 89
  • 111
0

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;
       }
    }
Auguste
  • 2,007
  • 2
  • 17
  • 25