如何在下拉列表中找到给定字符串值的索引?

时间:2010-10-18 07:07:59

标签: asp.net

我使用下拉列表,其中有4个值,以下是我的值

  • Uk-L1
  • Us-L1B
  • Aus-BUssness
  • UK-HSMP

在这里我需要选择一个特定的值作为一个选定的索引,我这样做的确切值和我的要求我将只传递' - '之后的值。所以我需要得到的值被选中,这里使用以下代码来选择它是不起作用可以任何一个帮助。

代码:

DropList.SelectedIndex = DropList.Items.IndexOf(DropList.Items.FindByValue("L1"));

感谢。

1 个答案:

答案 0 :(得分:6)

您可以尝试设置所选值:

DropDown.SelectedValue = DropDown.Items
    .OfType<ListItem>()
    .Where(l => l.Value.EndsWith("-L1B"))
    .First()
    .Value;

如果你想检查之前是否存在该值(如果找不到该值,First()扩展方法将抛出异常):

var item = DropDown.Items
    .OfType<ListItem>()
    .Where(l => l.Value.EndsWith("-L1B"))
    .FirstOrDefault();

DropDown.SelectedValue = (item != null) ? item.Value : null;
相关问题