how to insert checked items from checkedlistbox to SQL database?

I am trying to save checked items from a checkedlistbox to my SQL database and i am filling my checkedlistbox from the same SQL database,So far i am able to get the text of checked item from the checkedlistbox and i saved it in a string then i used a label to display if i am getting the text of checked item or not and its working but when i try to insert the checked data in database i get a error "Connection property has not been initialized." on ExecuteNonQuery() method.

Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim da As New SqlDataAdapter
        Dim dt As New DataTable
        Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
        Using conn As New SqlConnection(connectionString)
            conn.ConnectionString = connectionString
            conn.Open()
            Dim str As String
            str = "Select sem1 From sem"
            da = New SqlDataAdapter(str, conn)
            dt = New DataTable
            da.Fill(dt)
            CheckedListBox1.DataSource = dt
            CheckedListBox1.DisplayMember = "sem1"
            conn.Close()
        End Using
    End Sub


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


        Dim str As String
        Dim cmd As New SqlCommand
        Dim sql As String
        Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
        Using conn As New SqlConnection(connectionString)
            conn.Open()
            Dim itemChecked As Object
            For Each itemChecked In CheckedListBox1.CheckedItems
                str = itemChecked.item("sem1").ToString
                Label1.Text = str
                sql = "insert into pretab(pre) values('" + str + "')"
                cmd.ExecuteNonQuery()
            Next
            conn.Close()

        End Using

    End Sub
End Class

This error

sqlvb.net

Answers

answered 12 months ago Abdulfattah Alhazmi #1

The problem maybe arised from your query syntax. Try this:

sql = "insert into pretab(pre) values(@str)"
cmd.Parameters.AddWithValue("@str", str)            
cmd.ExecuteNonQuery()

OOPS.. I just realised that you forgot to assign your command with connection. So, please try to add the following statement:

cmd = New SqlCommand(sql, conn)

befor execution your command. So the final code should look like this:

sql = "insert into pretab(pre) values(@str)"

cmd = New SqlCommand(sql, conn)

cmd.Parameters.AddWithValue("@str", str) 

cmd.ExecuteNonQuery()

answered 12 months ago Karen Payne #2

First off I would do data operations in a class e.g. (note I focus on inserts). You need to change server and catalog to your server and catalog on SQL-Server.

Imports System.Data.SqlClient
Public Class Operations
    Private Server As String = "KARENS-PC"
    Private Catalog As String = "CheckedListBoxDatabase"
    Private ConnectionString As String = ""
    Public Sub New()
        ConnectionString = $"Data Source={Server};Initial Catalog={Catalog};Integrated Security=True"
    End Sub
    Public Function Read() As DataTable
        ' read rows for checked listbox here
    End Function
    Public Sub Insert(ByVal sender As List(Of String))
        Using cn As SqlConnection = New SqlConnection With {.ConnectionString = ConnectionString}
            Using cmd As SqlCommand = New SqlCommand With {.Connection = cn, .CommandText = "insert into pretab(pre) values (@pre)"}
                cmd.Parameters.Add(New SqlParameter With {.ParameterName = "@pre", .SqlDbType = SqlDbType.NVarChar})
                cn.Open()
                For Each item In sender
                    cmd.Parameters("@pre").Value = item
                    cmd.ExecuteNonQuery()
                Next
            End Using
        End Using
    End Sub
End Class

Form code

Public Class Form1
    Private ops As New Operations
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim Result = CheckedListBox1.Items.OfType(Of String).Where(Function(item, index) CheckedListBox1.GetItemChecked(index)).ToList
        ops.Insert(Result)
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        CheckedListBox1.DataSource = ops.Read
        CheckedListBox1.DisplayMember = "sem1"
    End Sub
End Class

answered 6 months ago SMHasnain #3

It appears that you did not provide the connection to the command. Your code was button click

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim str As String
    Dim cmd As New SqlCommand
    Dim sql As String
    Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
    Using conn As New SqlConnection(connectionString)
        conn.Open()
        Dim itemChecked As Object
        For Each itemChecked In CheckedListBox1.CheckedItems
            str = itemChecked.item("sem1").ToString
            Label1.Text = str
            sql = "insert into pretab(pre) values('" + str + "')"
            cmd.ExecuteNonQuery()
        Next
        conn.Close()

    End Using

End Sub

What you need to do is before cmd.ExecuteNonQuery() you need to provide it a connection cmd.connection = connectionString

this will remove the cmd.ExecuteNonQuery() error.

comments powered by Disqus