簡體   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