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.

Here is my code...

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

if (CheckBoxList1.Items.Selected)
{

str = CheckBoxList1.Items.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);

}

}

OK, from the top:
Firstly, please use [code] your code here [/code] tags when posting code. It maintains the formatting to make it easier to read.
Secondly, your for loop counter needs amending; if the Count of items in a collection is 5, then the index of the last item is 4. If you want to iterate through all items in the collection then your index should never be greater than 4. You can achieve this two ways; you can ensure index is less than Count (index < Count), or you can reduce Count by 1 and ensure your index is always less than or equal to it (index <= Count -1). You have done both. By stating i < CheckBoxList1.Items.Count - 1 you will always miss the last item in the CheckBoxList.
Finally, your SqlCommand; you create and open your connection and you create your sql query string, but you never execute it. You need to use cmd.ExecuteNonQuery() to actually run your query.

You might also want to consider placing your connection instantiation in a Using block to ensure it is correctly closed and disposed between calls:

using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        // Do work here; connection closed on following line.
    }

i have done exactly what u said but it is not working..Any suggestion r welcome..

This article has been dead for over six months. Start a new discussion instead.