繁体   English   中英

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

[英]How to search items from drop down list

我正在尝试搜索DropDown列表中的项目,但是下面的代码仅返回列表中最后一个项目的结果。 对于其余项目,它返回“国家不存在”,我该怎么做才能使代码对所有项目均有效。

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

这仅适用于最后一项,因为即使找到匹配项,您仍在循环播放。 例如,如果搜索框包含第一个项目,则循环应找到该项目,但随后它将对不匹配的第二个项目进行检查,并且标签文本将显示该国家/地区不存在(它确实)。 如果找到比赛,就应该break 像这样:

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

您可以尝试创建一种也可以检查您的方法:

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

     } 
     return false;
}

然后在按钮中单击处理程序:

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

HTH

发生这种情况的原因是,您正在运行一个循环,并尝试将搜索选项卡的文本与下拉列表进行比较,而不会在实际找到循环后就中断循环。 首先将标记变量初始化为false,然后输入if(item.Value == a),将标记标记为true并中断。 循环之后,检查标志是否为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