2016-06-23 13 views
1

這是我的問題。我有一個可以用關鍵字實現研究的文本框。我有一個有不同主題(ADV,Logistic,Finance,Administration)的清單框來過濾sql查詢。如果我搜索關鍵詞並檢查了「邏輯」,則返回結果將僅與「物流」相關。這很好,問題是,如果我檢查2複選框,例如「邏輯」和「財務」,我只會得到與「邏輯」相關的結果,但我想要得到2個結果。 20分鐘前,突然不再工作了,我不記得原因。誰能告訴我我錯過了什麼?從複選框過濾sql查詢的c#問題

這裏是我的代碼:

string word = tbSearch.Text; 

string strSql = @"SELECT CAST(ID as VarChar(50)) ID, Aggregation, DateDerniereSolution, DateDescription, DerniereSolution, DescriptionDemande, FileDeTraitement, NomContact, Numero, SousRubrique, TitreDemande 
       FROM cfao_DigiHelp_index.DigiHelpData WHERE (1 = 1)"; 

string selectedValue = ""; 
bool IsFirst = false; 
strSql += @" AND ("; 

foreach (ListItem item in CheckboxID.Items) 
{ 
    if (item.Selected) 
    { 
     selectedValue += item.Value ; 

     if (IsFirst) 
     { 
      strSql += " OR "; 
     } 

     strSql += " SousRubrique Like '%" + selectedValue + "%' "; 
     IsFirst = true; 
    } 

    if (CheckboxID.SelectedIndex == -1) 
    { 
     Label2.Visible = true; 
     Label2.Text = "Veuillez cocher au moins une rubrique"; 
    } 
} 

strSql += @" )"; 
+0

你能發表查詢嗎? – Berkay

+0

你的意思是'不再工作',你是否得到任何錯誤或沒有得到預期的輸出? –

回答

1

此行

selectedValue += item.Value ; 

肆虐查詢,因爲在每一個循環,你會保持串聯到了selectedValue選中項的值。只需使用item.Value

strSql += " SousRubrique Like '%" + item.Value + "%' "; 

而且,如果你檢查的項目與SousRubrique內容完全匹配,你可以儘量避免使用LIKE和野生搜索模式「%」,但只使用了相同操作

保持請記住,您需要嚴格控制checkedlistbox項目的內容,因爲如果您的用戶能夠爲SousRubrique編寫值,則您的代碼將暴露給Sql Injection攻擊。

+0

非常感謝! – Fanto