Reputation: 123
I'm trying to insert checkboxlist
multiple values in database,
Here is my insert code:
string str = string.Empty;
try
{
var sb = new StringBuilder();
var collection = ListLawCat.CheckedItems;
foreach (var item in collection)
{
str += item.Value + ",";
}
SqlConnection con = new SqlConnection();
con.ConnectionString = connString;
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "Insert into TABLE (COL1, COL2) values ('" + str + "','" + DocID + "') ";
com.CommandType = CommandType.Text;
con.Open();
int j = com.ExecuteNonQuery();
if (j > 0)
{
Response.Write("insert successfully");
Response.Write(str);
}
else
{
Response.Write("Not Inserted");
}
con.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
But this code will store all checkboxlist
values in one row.
Is that a way to store values in separate table rows?
Upvotes: 0
Views: 222
Reputation: 914
Try this
string str = string.Empty;
try
{
var sb = new StringBuilder();
SqlConnection con = new SqlConnection();
con.ConnectionString = connString;
SqlCommand com = new SqlCommand();
com.Connection = con;
var collection = ListLawCat.CheckedItems;
foreach (var item in collection)
{
com.CommandText = "Insert into TABLE (COL1, COL2) values ('" + item.Value+ "','" + DocID + "') ";
com.CommandType = CommandType.Text;
con.Open();
int j = com.ExecuteNonQuery();
if (j > 0)
{
Response.Write("insert successfully");
Response.Write( item.Value);
}
else
{
Response.Write("Not Inserted");
}
con.Close();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
Upvotes: 2