Reputation: 13
I have created a program (for school) that has create account, manage account (update and delete), and delete account. All functions work except for Update and I am not sure why. There's no error whatsoever, it just does nothing. Below is the code:
private void btnUpdate_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myCon"].ConnectionString);
con.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE Inventory SET ItemID=@ItemID, ItemName=@ItemName, ItemType=@ItemType, Quantity=@Quantity,WarehouseLocation=@WarehouseLocation,QuadrantNumber=@QuadrantNumber,BinNumber=@BinNumber,DateUpdated=@DateUpdated" +
" WHERE ItemID= '" + txtItemID.Text + "'", con))
{
if (txtItemID.Text == "@ItemID")
{
cmd.Parameters.AddWithValue("@ItemName", txtItemName.Text);
cmd.Parameters.AddWithValue("@ItemType", cmbType.Text);
cmd.Parameters.AddWithValue("@Quantity", udQuantity.Text);
cmd.Parameters.AddWithValue("@WarehouseLocation", cmbWarehouse.Text);
cmd.Parameters.AddWithValue("@QuadrantNumber", cmbQuadrant.Text);
cmd.Parameters.AddWithValue("@BinNumber", cmbBin.Text);
cmd.Parameters.AddWithValue("@DateUpdated", Convert.ToString(DateTime.Now));
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Item Updated!");
}
}
}
Upvotes: 1
Views: 52
Reputation: 410
This answer is based in assumption you already have this item in your DB and you just need to update it. I'll separate the answer in three steps:
First step: I assume your primary_key is the ItemID, so you shouldn't really update it as you're doing here:
UPDATE Inventory SET ItemID=@ItemID,...
You should just remove the ItemID = @ItemID, part, as we don't want to update it.
Second step: Now, this piece of code looks incorrect:
if (txtItemID.Text == "@ItemID")
It will try to match the txtItemID.Text with the string "@ItemID", which I believe it is not your goal, since I can understand it is your ID - It would be always false.
You should just remove this if.
Third step: You also need to change your where clause to have your ItemID as parameter, as below:
" WHERE ItemID=@ItemID", con))
Then add it to your parameters:
cmd.Parameters.AddWithValue("@ItemID", txtItemID.Text);
You should be good with these changes.
Another thing you could do is to always debug your application when you're struggling to understand a problem. It helps a lot!
Upvotes: 1