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

时间:2020-11-27 19:19:36

Iam using a dropdown list ,in that am having 4 values ,the following are my values

我使用下拉列表,因为我有4个值,以下是我的值

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

and here i need to choose the a particular value as a selected index ,and i did that for a exact value and in my requirement i will pass only the values after that '-' .so that i need get the value to be selected and here am using the following code to select it is not working can any one help for this.

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

Code:

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

Thanks.

1 个解决方案

#1


6  

You could try setting the selected value:

您可以尝试设置所选值:

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

And if you want to check if the value exists before (the First() extension method will throw an exception if the value is not found):

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

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

DropDown.SelectedValue = (item != null) ? item.Value : null;

#1


6  

You could try setting the selected value:

您可以尝试设置所选值:

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

And if you want to check if the value exists before (the First() extension method will throw an exception if the value is not found):

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

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

DropDown.SelectedValue = (item != null) ? item.Value : null;