在vb.net 2008中使用CheckedListBox

时间:2014-05-20 08:16:52

标签: vb.net

在vb.net 2008中,如何将Checkedlistbox中的多个选定数据插入到数据库sql server 2005中?

我的代码是

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
 Cn.Close()
        Cn.Open()
        Try
            cmd.CommandText = "insert into Module_Control_tbl (empl_ID,Module_ID) Values('" & ComboBox1.SelectedValue & "','" & CheckedListBox1.SelectedValue & "')"
            ComboBox1.Focus()
            cmd.Connection = Cn
            cmd.ExecuteNonQuery()
            MsgBox("Assign Module Successfully to Employee")
            Form7_Load(sender, e)
        Catch ex As Exception
            MsgBox(ex.Message)
            MsgBox("contact to Your System Administrator")
        End Try
        Cn.Close()

1 个答案:

答案 0 :(得分:0)

您应该遍历CheckedItems集合。

此外,您应始终使用参数来避免SQL注入。

以下是一个例子:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  Using cn As New SqlConnection("Connection String")
    cn.Open()
    Dim sb As New StringBuilder
    sb.AppendLine("INSERT INTO Module_Control_tbl")
    sb.AppendLine("(empl_ID, Module_ID)")
    sb.AppendLine("VALUES")
    sb.AppendLine("(@empl_ID, @module_ID)")
    For Each item In CheckedListBox1.CheckedItems
      Using cmd As New SqlCommand(sb.ToString, cn)
        cmd.Parameters.AddWithValue("@empl_ID", ComboBox1.SelectedValue.ToString)
        cmd.Parameters.AddWithValue("@module_ID", item.ToString)
        cmd.ExecuteNonQuery()
      End Using
    Next
  End Using
End Sub