简体   繁体   中英

How to search items from drop down list

I am trying to search the items in DropDown list but the code below only returns the result of the last item in the list. For rest of the items it returns "country does not exist" What should I do to make the code work for all the items.

  protected void SearchBtn_Click(object sender, EventArgs e)
    {
        string a = SearchCountryTb.Text;


        foreach (ListItem item in CountriesDD.Items)
        {
            if (item.Value == a)
            {
                YNLabel.Text = "country exixts";
            }
            else
            {
                YNLabel.Text = "country doesnot exist";
            }   
        }      
    }

This only works for the last item because you are still looping even after you've found a match. For example, if the search box contains the first item, the loop should find the item, but then it will perform the check on item two, which doesn't match, and the label text will say the country doesn't exist (when it does). You should break if you find a match. Like this:

foreach (ListItem item in CountriesDD.Items)
{
    if (item.Value == a)
    {
        YNLabel.Text = "country exists";
        break; //exit the loop if the item was found.
    }
    else
    {
        YNLabel.Text = "country doesnot exist";
    }  
} 

You could try creating a method that checks for you too:

bool CountryExists(string country)
{
    foreach (ListItem item in CountriesDD.Items)
    {
        if (item.Value == country)
        {
            return true;
        }

     } 
     return false;
}

And then in the button click handler:

if (CountryExists(SearchCountryTB.Text)) YNLabel.Text = "country exists";
else YNLabel.Text = "country does not exist";

HTH

This is happening because, you are running a loop and trying to compare the search tab text with the drop down list without breaking from the loop once you actually find it. Put a flag variable initialised to false first and in case you enter the if (item.Value == a) , mark the flag true and break. After the loop, check if the flag is true, then country exists, else doesn't.

boolean flag = false;
foreach (ListItem item in CountriesDD.Items) {
    if (item.Value == a) {
        flag = true;
        break; //exit the loop if the item was found.
    }
}
if(flag) {
    YNLabel.Text = "country exists";
} else {
    YNLabel.Text = "country doesn't exist";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM