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.
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));
This worked for me
foreach(ListItem li in dropdownlist.Items)
{
if (String.Compare(li.Text, myLabel.Text, true) == 0)
myCustomValidator.IsValid = false; // Match Found !
}
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");
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.