此 SqlCeParameterCollection 已包含具有此名称的 SqlCeParameter。错误

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

在这段代码中我有一个按钮点击事件。每当我第一次单击按钮时,代码都可以正常工作。但是,如果我在其他时候单击该按钮,则会引发错误。

我的密码是

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

您似乎第二次尝试将 @item 参数添加到您的命令中,这就是您收到错误消息的原因;

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

例如,您可以使用.Clear()方法在执行命令之前清除命令的参数。

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

当然,不要使用 AddWithValue 方法。 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 这样就一点都不贵了。

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

您的连接对象是此方法的外部全局对象。只是缩短它的生命周期,让它成为本地的:

conn.Open();

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

...

command.Dispose();