Laeeq A.
Laeeq A.

Reputation: 45

The SqlCeParameter with this name is already contained by this SqlCeParameterCollection. Error

In this code I have a button click event. Whenever I click the button first time, the code works fine. But if I click the button other time it throws the error.

My code is

private void button2_Click(object sender, EventArgs e)
{
    string itemname = comboBox1.SelectedItem.ToString();

    con.Open();

    command.CommandText = "DELETE FROM pricedata WHERE Item=@item";
    command.Connection = con;
    command.Parameters.AddWithValue("@item", itemname);

    command.ExecuteNonQuery();                
    con.Close();
}

Upvotes: 3

Views: 987

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98750

Looks like you try to add your @item parameter second time to your command and that's why you get an error as;

Hey! Your command has already this named parameter. You can't add the same named parameter to your command. That's meaningless.

You can use .Clear() method to clear your parameters of your command before you execute it for example.

command.Parameters.Clear();
command.Parameters.AddWithValue("@item", itemname);

And of course, don't use AddWithValue method. It may generate unexpected results sometimes. Use .Add() overloads to specify your parameter type and size. Would be better to use using statement to dispsoe your SqlCeConnection and SqlCeCommand automatically instead of calling Close or Dispose methods manually. And local connections are always preferable. It's best to open and close the connections as close as possible to their use. ADO.NET will do connection pooling so that this will not be expensive at all.

private void button2_Click(object sender, EventArgs e)
{
    using(var con = new SqlCeConnection(conString))
    using(var command = con.CreateCommand())
    {
       command.CommandText = "DELETE FROM pricedata WHERE Item = @item";
       command.Parameters.Clear();
       command.Parameters.AddWithValue("@item", comboBox1.SelectedItem.ToString());
       con.Open();
       command.ExecuteNonQuery();
    }                 
}

Upvotes: 6

Wiktor Zychla
Wiktor Zychla

Reputation: 48240

Your connection object is external, global to this method. Just shorten its lifetime, make it local:

conn.Open();

command = new SqlCeCommand();
command.Connection = conn; 

...

command.Dispose();

Upvotes: 0

Related Questions