Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 522
Lukas Avatar asked Dec 04 '12 00:12

Lukas


3 Answers

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;
like image 185
RAS Avatar answered Oct 21 '22 06:10

RAS


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");
like image 43
Nikola Davidovic Avatar answered Oct 21 '22 08:10

Nikola Davidovic


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
like image 30
foo-baar Avatar answered Oct 21 '22 06:10

foo-baar