【问题标题】:The variable name '@days' has already been declared. Variable names must be unique within a query batch or stored procedure变量名“@days”已被声明。变量名称在查询批处理或存储过程中必须是唯一的
【发布时间】:2016-03-06 20:44:29
【问题描述】:

我想在 sql server 中存储复选框列表的多个选定值。当我选择一个值时,它进入数据库,但在选择的多个时,它会给上面错误。

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>

【问题讨论】:

  • 有人请帮忙。提前致谢!

标签: asp.net checkboxlist


【解决方案1】:

我认为如果你想保存多个值,那么你首先构建你想保存的字符串,当你的 for each 准备好时添加它。

并且还要在最后一刻打开连接,不要忘记释放命令。

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();
}

【讨论】:

    【解决方案2】:

    我在循环内输入了插入查询,它解决了这个问题。感谢大家提出答案!

    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();
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2020-02-01
      • 2015-05-26
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2020-08-23
      相关资源
      最近更新 更多