Drop-down lists found at partial cost

To find an item (and select it) from the drop-down list using the value we just do

dropdownlist1.Items.FindByValue("myValue").Selected = true; 

How can I find an element using partial value? Say I have 3 elements and they have the meanings "myValue one", "myvalue two", "myValue three" respectively. I want to do something like

 dropdownlist1.Items.FindByValue("three").Selected = true; 

and select the last item.

+6
source share
3 answers

You can iterate from the end of the list and check if the value contains an element (this will select the last element that contains the value "myValueSearched").

  for (int i = DropDownList1.Items.Count - 1; i >= 0 ; i--) { if (DropDownList1.Items[i].Value.Contains("myValueSearched")) { DropDownList1.Items[i].Selected = true; break; } } 

Or you can use linq as always:

 DropDownList1.Items.Cast<ListItem>() .Where(x => x.Value.Contains("three")) .LastOrDefault().Selected = true; 
+12
source

You can iterate over the elements in your list, and when you find the first one whose line of elements contains a template, you can set the Selected property to true.

 bool found = false; int i = 0; while (!found && i<dropdownlist1.Items.Count) { if (dropdownlist1.Items.ToString().Contains("three")) found = true; else i++; } if(found) dropdownlist1.Items[i].Selected = true; 

Or you can write a method (or extension method) that will do this for you

 public bool SelectByPartOfTheValue(typeOfTheItem[] items, string part) { bool found = false; bool retVal = false; int i = 0; while (!found && i<dropdownlist1.Items.Count) { if (items.ToString().Contains("three")) found = true; else i++; } if(found) { items[i].Selected = true; retVal = true; } return retVal; } 

and name it as follows

 if(SelectByPartOfTheValue(dropdownlist1.Items, "three") MessageBox.Show("Succesfully selected"); else MessageBox.Show("There is no item that contains three"); 
+1
source

The above answers are perfect, there is simply no evidence of case sensitivity:

 DDL.SelectedValue = DDL.Items.Cast<ListItem>().FirstOrDefault(x => x.Text.ToLower().Contains(matchingItem)).Text 
+1
source

All Articles