繁体   English   中英

多项选择清单

[英]Multiple Choice CheckBoxList

我有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, "'", "''")) & "'"""

就像@Dai所说的那样,使用带文字值的in查询:

        '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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM