Search code examples
c#asp.netsqlcode-behind

Save list to database


This is what I have so far:

Veza.Open();
SqlCommand zadnjaN = new SqlCommand("SELECT TOP 1 id_n FROM Narudzba ORDER BY id_n DESC", Veza);
var id_zn = zadnjaN.ExecuteScalar(); //get 1 value for id_zn (last one entered)
List<int> proizvodi = new List<int>();
proizvodi = (List<int>)Session["kosarica"];
SqlCommand kupnja1 = new SqlCommand("INSERT INTO NarudzbaItemi ([narudzbaID], [proizvodID]) VALUES (@id_zn, @pro)", Veza);
for (int i = 0; i < proizvodi.Count; i++)
{
  kupnja1.Parameters.AddWithValue("pro", proizvodi[i]); //also tried @pro
  kupnja1.Parameters.AddWithValue("id_zn", id_zn); //@id_zn
  kupnja1.ExecuteNonQuery();
}
Veza.Close();

I get a message saying that variable name @pro has allready been declared. The point is, I need to insert a list of int items into column proizvodID, and however many times I insert a value in that column I need to insert an unchanging value that many times in column narudzbaID, which I get from a different table as the last value added. All 3 columns are int, and Session is List int. Using asp.net, c#, sql server 2008.


Solution

  • Here how you can do this. But John Saunders's method is better I think

        for (int i = 0; i < proizvodi.Count; i++)
        {
            //Add this line to clear parameters
            kupnja1.Parameters.Clear();
            kupnja1.Parameters.AddWithValue("pro", proizvodi[i]); //also tried @pro
            kupnja1.Parameters.AddWithValue("id_zn", id_zn); //@id_zn
            kupnja1.ExecuteNonQuery();
        }