dropdownlist项目按部分值查找

要使用我们简单的值,在下拉列表中查找项目(并选择它)

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

如何使用部分值找到项目? 假设我有3个元素,它们分别具有值“myValue one”,“myvalue two”,“myValue three”。 我想做点什么

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

并让它选择最后一项。

您可以从列表的末尾进行迭代,并检查值是否包含该项(这将选择包含值“myValueSearched”的最后一项)。

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

或者你可以像往常一样使用linq:

 DropDownList1.Items.Cast() .Where(x => x.Value.Contains("three")) .LastOrDefault().Selected = true; 

您可以迭代列表中的项目,当您找到其项目的字符串包含模式的第一个项目时,可以将其Selected属性设置为true。

 bool found = false; int i = 0; while (!found && i 

或者您可以编写一个方法(或扩展方法)来为您执行此操作

 public bool SelectByPartOfTheValue(typeOfTheItem[] items, string part) { bool found = false; bool retVal = false; int i = 0; while (!found && i 

并称之为这样

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

上面提到的答案是完美的,只是没有案例敏感性certificate:

 DDL.SelectedValue = DDL.Items.Cast().FirstOrDefault(x => x.Text.ToLower().Contains(matchingItem)).Text