2

I have this, and made a scope identity on another insert that makes the int id variable

foreach (ListItem item in CheckBoxList1.Items)
{
    if (item.Selected)
    {
        int CheckId = Convert.ToInt32(item.Value);
        cmd.CommandText = "INSERT INTO FarveTilCykel (fk_cy_id, fk_farve_id) VALUES (@cy, @farve)";

        cmd.Parameters.Add("@cy", SqlDbType.VarChar).Value = id;
        cmd.Parameters.Add("@farve", SqlDbType.VarChar).Value = CheckId;

        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
    } //end if
} //end foreach

The problem is (I think) that, when it has run it 1 time and does second, the @cy is already declared, how can I make it different for each time?

2
  • 2
    create every time command new object as well in loop Commented Feb 11, 2016 at 12:44
  • 1
    Which RDBMS is this for? Please add a tag to specify whether you're using mysql, postgresql, sql-server, oracle or db2 - or something else entirely. Commented Feb 11, 2016 at 12:50

3 Answers 3

4

You can't add the same parameters to a command more than once. You can Clear your parameters at the end of every iteration like;

foreach (ListItem item in CheckBoxList1.Items)
{
   ...
   ...
   cmd.Parameters.Clear();
}

Or better, define your parameters before your foreach and just add/change their values inside of it.

var parameter1 = new SqlParameter("@cy", SqlDbType.VarChar);
var parameter2 = new SqlParameter("@farve", SqlDbType.VarChar);    
cmd.Parameters.Add(parameter1);
cmd.Parameters.Add(parameter2);

foreach (ListItem item in CheckBoxList1.Items)
{
   ...
   ...
   cmd.Parameters["@cy"].Value = id;
   cmd.Parameters["@farve"].Value = CheckId;
}

Also use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.

Sign up to request clarification or add additional context in comments.

Comments

1

place

var p1 = cmd.Parameters.Add("@cy", SqlDbType.VarChar);
var p2 = cmd.Parameters.Add("@farve", SqlDbType.VarChar);

before the foreach block and

p1.Value = id;
p2.Value = CheckId;

inside the block instead of the 2 current lines.

Comments

1

I prefer open connection (conn) once and write it in using statement then clear parameters(cmd) for each record.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.