dropdownlist items find by partial value

2019-04-28 14:18发布

问题:

To find an item (and select it) in a dropdownlist using a value we simply do

dropdownlist1.Items.FindByValue("myValue").Selected = true;

How can I find an item using partial value? Say I have 3 elements and they have values "myValue one", "myvalue two", "myValue three" respectively. I want to do something like

dropdownlist1.Items.FindByValue("three").Selected = true;

and have it select the last item.

回答1:

You can iterate from the end of the list and check if value contains the item (this will select the last item which contains value "myValueSearched").

 for (int i = DropDownList1.Items.Count - 1; i >= 0 ; i--)
        {
            if (DropDownList1.Items[i].Value.Contains("myValueSearched"))
            {
                DropDownList1.Items[i].Selected = true;
                break;
            }
        }

Or you can use linq as always:

DropDownList1.Items.Cast<ListItem>()
                   .Where(x => x.Value.Contains("three"))
                   .LastOrDefault().Selected = true;


回答2:

You can iterate the items in your list, and when you find the first one whose items's string contains the pattern, you can set its Selected property to true.

bool found = false;
int i = 0;
while (!found && i<dropdownlist1.Items.Count)
{
       if (dropdownlist1.Items.ToString().Contains("three"))
              found = true;
       else
              i++;
}
if(found)
     dropdownlist1.Items[i].Selected = true;

Or you could write a method (or extension method) that does this for you

public bool SelectByPartOfTheValue(typeOfTheItem[] items, string part)
{
    bool found = false;
    bool retVal = false;
    int i = 0;
    while (!found && i<dropdownlist1.Items.Count)
    {
           if (items.ToString().Contains("three"))
                  found = true;
           else
                  i++;
    }
    if(found)
    {
           items[i].Selected = true;
           retVal = true;
    }
    return retVal;
}

and call it like this

if(SelectByPartOfTheValue(dropdownlist1.Items, "three")
     MessageBox.Show("Succesfully selected");
else
     MessageBox.Show("There is no item that contains three");


回答3:

Above mentioned answers are perfect, just there are not case sensitivity proof :

DDL.SelectedValue = DDL.Items.Cast<ListItem>().FirstOrDefault(x => x.Text.ToLower().Contains(matchingItem)).Text