Prabhakaran
Prabhakaran

Reputation: 1337

How to find the index of the given string value in dropdownlist?

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

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.

Upvotes: 0

Views: 3665

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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):

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

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

Upvotes: 6

Related Questions