我有2个国家和州的复选框列表。现在,当用户检查一个国家时,将出现的州名单仅来自该国家。但是,如果用户检查多个,我该怎么办?这是我的代码。我不知道如何在vb.net中制作for循环
cmd.CommandText = "SELECT distinct(a.AreaCode), b.AreaDescrip from tblUser a INNER JOIN tblArea b on a.AreaCode = b.AreaCode "
cmd.CommandText = cmd.CommandText & "WHERE CountryCode = N'" & Trim(Replace(cblCountry.SelectedValue, "'", "''")) & "'"""
答案 0 :(得分:0)
正如@Dai所说,使用in query,或者使用文字值:
'join selected items together
Dim selectedItems = String.Join("','", cblCountry.Items.Cast(Of ListItem)().Where(Function(li) li.Selected).Select(Function(li) li.Value))
'add joined string to command text
cmd.CommandText = "SELECT distinct(a.AreaCode), b.AreaDescrip from tblUser a INNER JOIN tblArea b on a.AreaCode = b.AreaCode " & _
"WHERE CountryCode IN ('" & selectedItems & "')"
或者最好使用参数化查询,在其中向命令文本添加参数名称,然后向命令对象添加参数,如下所示:
'get selected item values
Dim selectedItems = cblCountry.Items.Cast(Of ListItem)().Where(Function(li) li.Selected).Select(Function(li) li.Value)
'create a named parameter for each selected item - parameter0, parameter1 and so on
Dim parameters As String = String.Join(",", Enumerable.Range(0, selectedItems.Count()).Select(Function(x) "@parameter" + x))
'Add parameter names to command text
cmd.CommandText = "SELECT distinct(a.AreaCode), b.AreaDescrip from tblUser a INNER JOIN tblArea b on a.AreaCode = b.AreaCode " & _
"WHERE CountryCode IN (" & parameters & ")"
'add parameters to command object with values from selected items
For p As Integer = 0 To selectedItems.Count() - 1
cmd.Parameters.AddWithValue("@parameter" + p, selectedItems(p))
Next