select dropdown list item findbytext without case

2020-05-27 11:04发布

问题:

I want to select one item in drop down list in ASP.NET written with VB.NET - I have values and texts in listbox like this:

Volvo
Audi
etc...

But values coming from other place in upper case... VOLVO, AUDI..

This code:

dropdownlist.FindByValue("CAPITAL")

Is not working and giving null for Volvo.. please help.

回答1:

One way would be LINQ:

Dim volvoItem = dropdownlist.Items.Cast(Of ListItem)().
    FirstOrDefault(Function(i) i.Text.Equals("Volvo", StringComparison.InvariantCultureIgnoreCase))

C#:

var volvoItem = dropdownlist.Items.Cast<ListItem>()
   .FirstOrDefault(i => i.Text.Equals("Volvo", StringComparison.InvariantCultureIgnoreCase));


回答2:

This worked for me

foreach(ListItem li in dropdownlist.Items)
    {
        if (String.Compare(li.Text, myLabel.Text, true) == 0)
            myCustomValidator.IsValid = false;  // Match Found !
    }


回答3:

Like Tim said LINQ would be you answer.
in C# try the following:

var item = dropdownlist.Items.Cast<ListItem>().SingleOrDefault(li =>
                                               li.Text.ToUpper() == "VOLVO");


回答4:

Additional variants, using framework CI comparison. VB:

uiList.Items.Cast(Of ListItem)
  .FirstOrDefault(Function(i) i.Text.Equals(comparand, StringComparison.InvariantCultureIgnoreCase))

C#:

uiList.Items.Cast<ListItem>()
  .FirstOrDefault(i => i.Text.Equals(comparand, StringComparison.InvariantCultureIgnoreCase));

You could also use CurrentCultureIgnoreCase depending on your requirements. These are generally safer than comparing with ToUpper/ToLower, because some cultures have unexpected casing rules.