简体   繁体   中英

No value given for one or more required parameters. C#

I have a C# program and I made a code for subtracting the amount of sold products from the amount of these products in the stock (access datatable) so I used this code :

foreach (DataGridViewRow r in dataGridView1.Rows)
{
      OleDbCommand command = new OleDbCommand("Update BookInserting set Amount = Amount - '" + Convert.ToInt32(r.Cells[1].Value) + "' where BookName = " + r.Cells[0].Value.ToString() + "", connection);
      connection.Open();
      command.ExecuteNonQuery();
      connection.Close();
}

but when I run it gives me this error : (No value given for one or more required parameters) . I tried solving it several times but failed, I hope you can help me solve it. Thanks in advance.

Your problem is probably caused by Access unable to recognize some part of your query as an object of the underlying table (or the table itself).
This problem and a more serious one called Sql Injection could be avoided using parameters. (And a side benefit your code becomes a lot clearer without all those strings concatenations)

So let's try to change your code in this way:

// String sql with parameters placeholders 
string cmdText = @"Update BookInserting 
                   set Amount = Amount - @amt
                   where BookName = @book";

connection.Open();

// Just build the command just one time outside the loop and 
// add the two parameters required (without a value and in the exact order
// expected by the placeholders
OleDbCommand command = new OleDbCommand(cmdText, connection);
command.Parameters.Add("@amt", OleDbType.Integer);
command.Parameters.Add("@book", OleDbType.VarWChar);

// Inside the loop just change the parameters values and execute
foreach (DataGridViewRow r in dataGridView1.Rows)
{
    // If the cell with the parameter for the WHERE 
    // clause is invalid skip the update
    if(!r.IsNewRow && r.Cells[0].Value != null  
                   && r.Cells[0].Value.ToString() != "")
    {
       cmd.Parameters["@amt"].Value = Convert.ToInt32(r.Cells[1].Value);
       cmd.Parameters["@book"].Value = r.Cells[0].Value.ToString();
       command.ExecuteNonQuery();
    }

}
connection.Close();

Final note. A connection object should be created each time you require it. From your code it is not clear if this is the case. Use the following pattern. ( Using Statement )

using(OleDbConnection connection = new OleDbConnection(....))
{
    ... code that uses the connection ....
} // <- here the connection is closed and disposed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM