How to add all value from checkbox list
-
How am i to insert all my selected items from checkbox list to my database. Right now i only able to insert 1 item to my database even I have select 2 items from my checkboxlist. my code is as below. mycommand2 = New SqlCommand("INSERT INTO t_userpackage (userID, packageID) VALUES (@userid, @packageid)", myconnection) mycommand2.Parameters.Add("@userid", SqlDbType.Int, 4).Value = ddluser.SelectedValue mycommand2.Parameters.Add("@packageid", SqlDbType.Int, 4).Value = chkpackage.SelectedItem.Value mycommand2.ExecuteNonQuery()
-
How am i to insert all my selected items from checkbox list to my database. Right now i only able to insert 1 item to my database even I have select 2 items from my checkboxlist. my code is as below. mycommand2 = New SqlCommand("INSERT INTO t_userpackage (userID, packageID) VALUES (@userid, @packageid)", myconnection) mycommand2.Parameters.Add("@userid", SqlDbType.Int, 4).Value = ddluser.SelectedValue mycommand2.Parameters.Add("@packageid", SqlDbType.Int, 4).Value = chkpackage.SelectedItem.Value mycommand2.ExecuteNonQuery()
You only have one item because you only ask one item, loop through your checkboxes with some kind of loop. (syntax will not be correct but you'll get the meaning i hope)
foreach(CheckBox chxChecked in chkpackage.SelectedItems){
// save here to the database this one item
} -
You only have one item because you only ask one item, loop through your checkboxes with some kind of loop. (syntax will not be correct but you'll get the meaning i hope)
foreach(CheckBox chxChecked in chkpackage.SelectedItems){
// save here to the database this one item
}I trying to loop too but i failed. What is the syntax for looping. BElow is what i done but it is wrong. Dim i As Integer For i = 0 To chkpackage.SelectedItem.Count - 1 mycommand2.Parameters.Add("@packageid", SqlDbType.Int, 4).Value = chkpackage.SelectedItem.Value End If Next
-
I trying to loop too but i failed. What is the syntax for looping. BElow is what i done but it is wrong. Dim i As Integer For i = 0 To chkpackage.SelectedItem.Count - 1 mycommand2.Parameters.Add("@packageid", SqlDbType.Int, 4).Value = chkpackage.SelectedItem.Value End If Next
I guess the loop is allright, but i'm not familiar with VB.NET, but i can see that there is a logical mistake in your code. You're trying to add each time inside your loop the same parameter. But you need each time you loop a new command which is going to insert the data into your database. Once that is done, then you can step to the next item. For your information, maybe you can get some information out of it to transform it to VB.Net i've sketched it in C#:
CheckBoxList chkList = new CheckBoxList(); foreach(CheckBox chkBox in chkList.Items) { if(chkBox.Checked) { // make your command // add your parameters // save to the database } }