在单独的表格行中插入值

本文关键字:插入 表格 单独 | 更新日期: 2023-09-27 17:57:03

我正在尝试在数据库中插入checkboxlist多个值,

这是我的插入代码:

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

但是此代码会将所有checkboxlist值存储在一行中。

这是一种将值存储在单独的表行中的方法吗?

在单独的表格行中插入值

试试这个

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