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

时间:2014-05-22 13:14:21

标签: c# asp.net database

代码是:

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数据库。然而, 没有任何东西进入数据库,因此,想知道是否有任何解决方案来解决这个问题。谢谢!

1 个答案:

答案 0 :(得分:0)

我重构了你的代码,所以它会起作用。一些评论是内联的。我假设您正在插入一个包含单列的表。

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()。我没有测试过代码,但是应该这样做