2014-02-15 54 views
1

我想在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"; 
      } 
     }  
    } 

回答

1

這隻適用於最後一個項目,因爲即使找到匹配項,仍然還在循環。例如,如果搜索框中包含第一個項目,則循環應該找到該項目,但是它將對項目2執行不匹配的檢查,並且標籤文本會說該國家不存在(何時它確實)。如果您找到匹配項,您應該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

+0

謝謝你的工作 – Shrugo

+0

當然!如果它有幫助,請隨時將其標記爲答案。 :) – davidsbro

1

這發生的原因是,您正在運行一個循環,並試圖將搜索選項卡文本與下拉列表進行比較一旦你真的找到它,就不會從循環中突破。首先將一個標誌變量初始化爲假,如果您輸入if(item.Value == a),則將標誌標記爲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"; 
}