To insert multiple checkbox list values into database in single column using c#

Neetika
Posted by Neetika under C# category on | Views : 33634
here is my code .

I am trying to insert mutiple checkbox list values in my sql database in single column..only one value is inserting because of insert statement.i want multiple values to be inserted.For loop is not working..any help would be appreciated.

for (int i = 0; i < CheckBoxList1.Items.Count - 1; i++)
{
String str = "";

if (CheckBoxList1.Items[i].Selected)
{

str = CheckBoxList1.Items[i].Text;

con.Open();

string sql = "Insert into LibManAddBook(Category,BookTitle,Feature,SubCategory)values('" + DDLCategory.SelectedItem.Text + "','" + TxtBooktitle.Text + "','" + CheckBoxList1.Text + "','" + DDLSubcategory.SelectedItem.Text + "')";

SqlCommand cmd = new SqlCommand(sql, con);

Comments or Responses

Posted by: Shankul2784 on: 8/3/2010 Level:Bronze | Status: [Member]
Hi,

Following will help you-

String str = "";

for (int i = 0; i < CheckBoxList1.Items.Count - 1; i++)
{

if (CheckBoxList1.Items.Selected)
{

if(str=="")
str = CheckBoxList1.Items.Text;
else
str += ","+ CheckBoxList1.Items.Text;

}
}
con.Open();

string sql = "Insert into LibManAddBook(Category,BookTitle,Feature,SubCategory)values('" + DDLCategory.SelectedItem.Text + "','" + TxtBooktitle.Text + "','" + str + "','" + DDLSubcategory.SelectedItem.Text + "')";

SqlCommand cmd = new SqlCommand(sql, con);
Posted by: Neetika on: 8/4/2010 Level:Starter | Status: [Member]
thanks a lot...Its working now.
Posted by: Moon123 on: 12/7/2012 Level:Starter | Status: [Member] | Points: 10
I had the same problem and I used the following code to insert multiple checkbox values into SQL Server database but still only the first value selected gets inserted .Could you please help me why it is happening.
Following is my code
string str = "";
for (int i = 0; i < audience.Items.Count; i++)
{

if (audience.Items[i].Selected)
{

if (str == "")
str = audience.Items[i].Text;
else
str += "," + audience.Items[i].Text;

}
}


cmd.Parameters.AddWithValue("@EventAudience", audience.Text);




where audience = CheckBoxListItem ID and EventAudience is the column name where I want to insert the values

Thanks in advance .

Login to post response