简体   繁体   English

如何从下拉列表中搜索项目

[英]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. 我正在尝试搜索DropDown列表中的项目,但是下面的代码仅返回列表中最后一个项目的结果。 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. 如果找到比赛,就应该break 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 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. 首先将标记变量初始化为false,然后输入if(item.Value == a),将标记标记为true并中断。 After the loop, check if the flag is true, then country exists, else doesn't. 循环之后,检查标志是否为true,然后国家/地区存在,否则不存在。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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