列表框项值未保存到数据库

本文关键字:保存 数据库 列表 | 更新日期: 2023-09-27 18:04:41

代码为:

protected void bn_add_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["FYP"].ConnectionString);
        string str;
        SqlCommand com;
        conn.Open();
        for (int i = 0; i < listbox_selected.Items.Count; i++)
        {
            if (listbox_selected.Items[i].Selected == true)
            {
                str = "INSERT INTO Competency_TechnicalSkill('" + listbox_selected.Items[i].ToString() + "')";
                com = new SqlCommand(str, conn);
                com.ExecuteNonQuery();
            }
        }

我已经多次尝试将数据插入到Competency_TechnicalSkill数据库。然而,没有任何东西进入数据库,因此,我想知道是否有任何解决这个问题的方法。谢谢你!

列表框项值未保存到数据库

我已经重构了你的代码,所以它将工作。有些注释是内联的。我假设您正在插入一个只有单列的表。

protected void bn_add_Click(object sender, EventArgs e)
{
    // good idea to check if you have selected items
    if (listbox_selected.SelectedIndex == -1) return;
    // using will take care of closing and disposing
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["FYP"].ConnectionString))
    {
        conn.Open();
        using (SqlCommand command = new SqlCommand())
        {
            command.CommandType = CommandType.Text;
            // if your listbox is multiselect, all you need is to check 'selected items'
            foreach (ListItem item in listbox_selected.Items)
            {
                if (item.Selected == true)
                {
                    // here you didn't have 'values' in your sql query
                    command.CommandText = "INSERT INTO Competency_TechnicalSkill values('" + item.ToString() + "')"; 
                    // if your table has more than one column you need to use: insert into table (col1) values ('data')            
                    command.ExecuteNonQuery();
                }
            }
        }
   }
}

现在,注意,如果您的listbox项已经是字符串,则不需要调用.ToString()。我还没有测试代码,但这应该可以做到