C# – How to Search Through a C# DropDownList Programmatically


I am having a hard time figuring out how to code a series of "if" statements that search through different dropdownlists for a specific value entered in a textbox. I was able to write code that finds a specific value in each dropdownlist; but, before this happens, I need to add an "if" statement saying, "if dropdownlist doesn't contain the specific value, go to next if statement, and so on". The following is an example of what I have so far:

if (dropdownlist1.SelectedValue == textbox1)
  dropdownlist1.SelectedIndex = dropdownlist1.items.indexof(dorpdownlist1.items.findbyvalue(textbox1.text) ...

if (dropdownlist2.SelectedValue == textbox1)
  dropdownlist2.SelectedIndex = dropdownlist2.items.indexof(dorpdownlist2.items.findbyvalue(textbox1.text) ...


What this does is reads or scans the first value or index in each dropdownlist, based off of my entry in textbox1. Unfortunately, it only identifies the first value or index. I need to figure out how to scan through the entire dropdownlist for all values per each "if" statement to find the matching textbox1 value. Does anyone have any suggestions?

Thank you,


Best Solution

foreach (ListItem li in dropdownlist1.Items)
    if (li.Value == textBox1.text)
       // The value of the option matches the TextBox. Process stuff here.

That is my suggestion for how to see if the value is in the dropdownlist.

Related Question