简体   繁体   中英

Multiple Choice CheckBoxList

I have 2 checkboxlist which is country and state. now, when a user check one country, the list of state that will come out is only from that country. But how do i do when user check more than one? here is my code. I'm not sure how to make a for loop in vb.net

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

As @Dai said, use an in query, either with literal values:

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

Or preferably by using a parameterised query where you are adding parameter names to your command text and then adding parameters to your command object, something like this:

        '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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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