Lukas
Lukas

Reputation: 2923

dropdownlist items find by partial value

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.

Upvotes: 8

Views: 15884

Answers (3)

RAS
RAS

Reputation: 3385

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;

Upvotes: 15

foo-baar
foo-baar

Reputation: 1104

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

Upvotes: 1

Nikola Davidovic
Nikola Davidovic

Reputation: 8656

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");

Upvotes: 1

Related Questions