要使用值我们在下拉列表中查找项目(并选择它),我们只需
dropdownlist1.Items.FindByValue("myValue").Selected = true;
如何使用部分值找到项目?假设我有3个元素,它们分别具有值“myValue one”,“myvalue two”,“myValue three”。我想做像
这样的事情dropdownlist1.Items.FindByValue("three").Selected = true;
并选择最后一项。
答案 0 :(得分:13)
您可以从列表末尾进行迭代,并检查值是否包含该项(这将选择包含值“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<ListItem>()
.Where(x => x.Value.Contains("three"))
.LastOrDefault().Selected = true;
答案 1 :(得分:1)
您可以迭代列表中的项目,当您找到第一个项目的字符串包含模式时,您可以将其Selected属性设置为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;
或者您可以编写一个为您执行此操作的方法(或扩展方法)
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;
}
并像这样称呼它
if(SelectByPartOfTheValue(dropdownlist1.Items, "three")
MessageBox.Show("Succesfully selected");
else
MessageBox.Show("There is no item that contains three");
答案 2 :(得分:1)
上面提到的答案是完美的,只是没有案例敏感性证明:
DDL.SelectedValue = DDL.Items.Cast<ListItem>().FirstOrDefault(x => x.Text.ToLower().Contains(matchingItem)).Text