Muhammad Usman
Muhammad Usman

Reputation: 9

Update query is not working - help needed

private void Update_Click(object sender, EventArgs e)
{
    string loca="Pakistan";

    OleDbConnection con = new   OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Usman\\Desktop\\db.accdb");

    OleDbCommand com = new OleDbCommand("Update INVENTORY SET Location=? WHERE itemID='1' ", con);
    com.Parameters.Add("@loca", OleDbType.VarChar).Value = loca;

    con.Open();

    try
    {
        com.ExecuteNonQuery();
    }
    catch(Exception f)
    {
        MessageBox.Show(f.Message);
        //MessageBox.Show("Given Data is not Valid", "Cannot Add", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

    con.Close();

    gridview();
}

Here I have changed the code no error m getting is

No value given for one or more required parameters

Update query is not working so please help me with it.

Upvotes: 0

Views: 76

Answers (1)

D Stanley
D Stanley

Reputation: 152491

In C# you need to add an actual parameter object and give it a value:

string loca="Pakistan";
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Usman\\Desktop\\db.accdb");

OleDbCommand com = new OleDbCommand("Update INVENTORY SET Location= ? WHERE itemID='1'", con);
com.Parameters.Add("@loca", OleDbType.VarWChar).Value = loca ?? (object)DBNull.Value;

Some other suggestions/habits to get in to:

  • Wrap your connections and commands in using blocks so that they get disposed of in a timely manner
  • Do not just catch an exception and show a vague message. Either include the exception details or log it somewhere so that you know what the actual error is.

Upvotes: 3

Related Questions