我想在sql server中存储checkboxlist的多个选定值。当我选择一个值时,它进入数据库但是当选择多个时,它会给出上述错误。
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["IvrContext"].ConnectionString);
conn.Open();
SqlCommand com1 = new SqlCommand("INSERT into Ivrdatas (days) values (@days)", conn);
string empty = "";
foreach (ListItem lst in CheckBoxList1.Items)
{
if (lst.Selected == true)
{
empty = empty + " " + lst.Value;
com1.Parameters.AddWithValue("@days", empty);
com1.ExecuteNonQuery();
}
}
conn.Close();
}
这是我的HTML。
<asp:CheckBoxList ID="CheckBoxList1" runat="server" style="margin-left: 299px" AutoPostBack="True">
<asp:ListItem>Monday</asp:ListItem>
<asp:ListItem>Tuesday</asp:ListItem>
<asp:ListItem>Wednesday</asp:ListItem>
<asp:ListItem>Thursday</asp:ListItem>
<asp:ListItem>Friday</asp:ListItem>
<asp:ListItem>Saturday</asp:ListItem>
<asp:ListItem>Sunday</asp:ListItem>
</asp:CheckBoxList>
答案 0 :(得分:1)
我认为如果您想保存多个值,那么首先要构建要保存的字符串,并在每个字符串准备就绪时添加它。
并在最后一刻打开连接,不要忘记处理命令。
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["IvrContext"].ConnectionString);
SqlCommand com1 = new SqlCommand("INSERT into Ivrdatas (days) values (@days)", conn);
string empty = "";
foreach (ListItem lst in CheckBoxList1.Items)
{
if (lst.Selected == true)
{
empty = empty + " " + lst.Value;
}
}
com1.Parameters.AddWithValue("@days", empty);
conn.Open();
com1.ExecuteNonQuery();
com1.Dispose();
conn.Close();
}
答案 1 :(得分:-1)
我在循环内输入了插入查询,它解决了问题。谢谢每个人提出建议答案!
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["IvrContext"].ConnectionString);
conn.Open();
string empty = "";
foreach (ListItem lst in CheckBoxList1.Items)
{
if (lst.Selected == true)
{
empty = lst.Value;
SqlCommand com1 = new SqlCommand("INSERT into Ivrdatas (days) values ('" + empty + "')", conn);
com1.ExecuteNonQuery();
}
}