1

I am new to working on vb.net 2008 and SQL Server 2005. I want to insert multiple selected check box values from a checkedlistbox at one click of insert button in vb.net.

Can anyone show me how I can do this?

My code is:

Dim Checkeditems As Integer

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    cmd.CommandText = ("Insert into Modules where Module_Name=@Module_Name")
    cmd.Connection = cn
    cn.Open()
    For Each Checkeditem In CheckedListBox1.SelectedValue.ToString
        cmd.Parameters.AddWithValue("@Module_Name", Checkeditem)
    Next
    MsgBox("inserted", MsgBoxStyle.OkOnly)
    cn.Close()
End Sub

This is how I fill the CheckedListBox

qry = "Select Module_ID,Module_Name from Modules" 
da = New SqlDataAdapter(qry, cn) 
ds = New DataSet() 
da.Fill(ds, "tab") 
CheckedListBox1.DataSource = ds.Tables("tab") 
CheckedListBox1.DisplayMember = "Module_Name" 
CheckedListBox1.ValueMember = "Module_ID" 
CheckedListBox1.Text = ""
Steve
  • 213,761
  • 22
  • 232
  • 286
mano
  • 11
  • 1
  • 3

2 Answers2

2

the first thing you must correct is that their is no where condition is allowed with Insert command.

If you want to insert multiple rows in a single query means you con refer this link or try the following,

Dim sql as String="Insert into Modules (Module_Nam) VALUES "
For Each itemChecked In CheckedListBox1.CheckedItems
    sql & = "('" &  itemChecked.ToString & "'),"
Next
cmd.CommandText = sql.SubString(0,Len(sql)-1) '<-- avoid an additional comma
cmd.Connection = cn
cn.Open()
cmd.ExecuteNonQuery()
MsgBox("inserted", MsgBoxStyle.OkOnly)
cn.Close()
Community
  • 1
  • 1
  • Semicorrect. A part from the part about MULTIPLE SELECTED CHECKBOXES – Steve Nov 06 '14 at 11:35
  • [CheckedListBox.CheckedIndices](http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.checkedindices(v=vs.110).aspx), and now it is worse because the Items is not a collection of checkboxes. – Steve Nov 06 '14 at 12:23
  • hello Neethu Soman your code is helping me but its showing an error that is Incorrect syntax near 'System.Data.DataRowView' on (cmd.ExecuteNonQuery) – mano Nov 07 '14 at 07:44
  • my code Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim sql As String = "Insert into Modules (Module_Name) VALUES" For Each itemChecked In CheckedListBox1.CheckedItems sql &= "('" & itemChecked.ToString & "')" Next cmd.CommandText = sql.Substring(0, Len(sql) - 1) '<-- avoid an additional comma cmd.Connection = cn cn.Open() cmd.ExecuteNonQuery() MsgBox("inserted", MsgBoxStyle.OkOnly) cn.Close() – mano Nov 08 '14 at 04:38
1

The answer from Neethu Soman is steering you in the right direction but contains some errors and some inefficiencies.

First point: if you have many elements in your checklist it is better to use a StringBuilder class to avoid too many string concatenations.
Second point: you should loop over the CheckedIndices property to retrieve the Item text to insert avoiding an unnecessary loop over all the items.

Dim sql = new StringBuilder("Insert into Modules (Module_Nam) VALUES ")
For Each c In CheckedListBox1.CheckedIndices
    Dim value = CheckedListBox1.Items(c).ToString
    sql.Append("('" &  value & "'),"
Next
sql.Length -= 1 ' Remove the last comma '
cmd.CommandText = sql.ToString()
cmd.Connection = cn
cn.Open()
Dim rowsInserted = cmd.ExecuteNonQuery()
MsgBox("inserted " & rowsInserted & " rows", MsgBoxStyle.OkOnly)
cn.Close()

EDIT

From your comment below then every Item in the CheckedListBox is a DataRowView and when you want to get back the values checked you need to use a DataRowView object

Dim sql = new StringBuilder("Insert into Modules (Module_Name) VALUES ")
For Each c In CheckedListBox1.CheckedIndices
    Dim rowView As DataRowView = CheckedListBox1.Items(c)
    Dim value = rowView("Module_Name").ToString()
    sql.Append("('" &  value & "'),"
Next
sql.Length -= 1 ' Remove the last comma '
cmd.CommandText = sql.ToString()
cmd.Connection = cn
cn.Open()
Dim rowsInserted = cmd.ExecuteNonQuery()
MsgBox("inserted " & rowsInserted & " rows", MsgBoxStyle.OkOnly)
cn.Close()

This will fix the error in reading back the checked values, but I am a bit perplexed by your code. You have a table named Modules from wich you read the id and the name of the modules. Then you write code that INSERT again the Module name in the same table? You end up with duplicate module names in that table (if the Module_Name is not an unique index in that table). Is this really what you are trying to do?

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • and if i am using this code then first tell me how i am using two clases at a time – mano Nov 08 '14 at 06:11
  • What do you mean with _two clases at a time_? This _condition_ is not present in your original question – Steve Nov 08 '14 at 08:44
  • My code is this please check it here is showing arror on the Dim Builder As New System.Text.StringBuilder on Builder type that error is : Error 1 Overload resolution failed because no accessible 'New' can be called without a narrowing conversion: 'Public Sub New(value As String)': Argument matching parameter 'value' narrows from 'Object' to 'String'. 'Public Sub New(capacity As Integer)': Argument matching parameter 'capacity' narrows from 'Object' to 'Integer'. and my code is : on next comment – mano Nov 10 '14 at 05:01
  • Private Sub StringBuilder() Dim Builder As New System.Text.StringBuilder("Insert into Modules (Module_Name) VALUES('" & CheckedListBox1.SelectedItem & "')") For Each c In CheckedListBox1.CheckedItems Dim value = CheckedListBox1.Items(c) Builder.Append("Module_Name ('" & CheckedListBox1.SelectedValue & "'") Next Builder.Length -= 1 ' Remove the last comma ' cmd.CommandText = Builder.ToString() cmd.Connection = cn – mano Nov 10 '14 at 05:06
  • Of course, you have changed the code posted and now it makes no sense. SelectedItem is a property of type object, you need a ToString when passing to the StringBuilder constructor. But why you changed the code in that way? Now you don't have anymore the comma required to pass multiple inserts, and the sql produced is not valid. – Steve Nov 10 '14 at 08:23
  • This is an example of how your query should be at the end of the loop http://blog.sqlauthority.com/2008/07/02/sql-server-2008-insert-multiple-records-using-one-insert-statement-use-of-row-constructor/ – Steve Nov 10 '14 at 08:26
  • this error is showing when i am clicking on Insert button and my code is : Private Sub Stringbuilder() Dim Builder As New System.Text.StringBuilder("Insert into ruff_Module (Module_Name) VALUES") For Each c In CheckedListBox1.CheckedIndices Dim values = CheckedListBox1.Items(c) Builder.Append("('" & values & "')") – mano Nov 11 '14 at 04:52
  • Next Builder.Length -= 1 cmd.CommandText = Builder.ToString() cmd.Connection = cn – mano Nov 11 '14 at 04:53
  • cn.Open() Dim rowsInserted = cmd.ExecuteNonQuery() MsgBox("inserted " & rowsInserted & " rows ", MsgBoxStyle.OkOnly) cn.Close() End Sub – mano Nov 11 '14 at 04:53
  • Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Stringbuilder() End Sub please check these all comments and please help me out to remove this error – mano Nov 11 '14 at 04:53
  • Can you exaplain exactly what error do you receive from the exact above code? Remember Items is a property that can contain anything from a simple string to any complex object depending on how do you fill the combo initially. If it is a string then you need to add ToString() to the line that extract the Items(c) value, if it is something different like a DataRowView then you need to identify the column to use Items(c)(????). Change your original question adding the code that initializes the combo with data. – Steve Nov 11 '14 at 08:50
  • the error is : Operator '&' is not defined for string "('" and type 'DataRowView'...... on the line of ... Builder.Append("('" & values & "')") – mano Nov 11 '14 at 10:27
  • So the Items in the Combobox are DataRowView not simple strings. This complicates the matter a bit. To give the correct answer you need to update your question (use the edit button) adding the code used to fill the combo (including, if any, the values of the properties ValueMember and DisplayMember) and tell me what value you want to extract from the DataRowView – Steve Nov 11 '14 at 11:08
  • first thing i am not using combobox i am using Checked list box in which loading modules from database . and i want to insert these selected modules from modules table to next table using checkedlistbox... – mano Nov 12 '14 at 03:47
  • this code of loadng table on checkedlist box: qry = "Select Module_ID,Module_Name from Modules" da = New SqlDataAdapter(qry, cn) ds = New DataSet() da.Fill(ds, "tab") CheckedListBox1.DataSource = ds.Tables("tab") CheckedListBox1.DisplayMember = "Module_Name" CheckedListBox1.ValueMember = "Module_ID" CheckedListBox1.Text = "" – mano Nov 12 '14 at 07:10
  • oh yes i know what you are saying actually i want to add these module_Name which are showing in checkedluist box insert to ruff_Modules table but its not working .... me just change the name of Module like ruff_Module and the fields are same. so how can i use this and when i am using this then it showing an error : Incorrect syntax near 'Physics'. here Physics is the module name . – mano Nov 13 '14 at 05:34
  • Steve yuor editable code is working but it only can insert one value at a time not multiple selected checkbox value – mano Nov 18 '14 at 06:47
  • Try to use a debugger and check what is the value returned by sql.ToString(). This should be in the form of _"insert (field1, fieldN) (FirstValueForField1, FirstValueForFieldN), (SecondValueForField1, SecondValueForFieldN), ..... "_ until the last checked index
    – Steve Nov 18 '14 at 08:55
  • I am willing to help you, but you should be able to use a debugger. Set a breakpoint on the line _"cmd.CommandText = sql.ToString()"_ pressing F9, start with F5. When your code flow reach that point it stops and you will see the value of the variable sql looking at the LocalWindow. This is the value that get passed to the command and you should be able to see if it conforms to the pattern required by the [multiple SQL insert syntax](http://stackoverflow.com/questions/2624713/how-do-i-insert-multiple-rows-without-repeating-the-insert-into-dbo-blah-part) – Steve Nov 18 '14 at 10:11