Having a problem updating table in Linq to Entities with update statement but not updating the table
I have a form with add, edit, and save buttons. The form also has a datagridview.
I have done this to update existing product entities and to add new product entities, then display the altered data in the datagridview.
When I click on edit button, the save button will be displayed and the statements that I have written in save button is executed.
New product entities add just fine.
My problem is that when I click on the edit button, anew row is added to datagridview instead of updating the same row.
Is there any way to check the condition whether the available product in table is updating or adding a new product before adding to table in entity framework?
private void btnSave_Click(object sender, EventArgs e)
{
pictureBox1.Enabled = true;
开发者_运维知识库 pictureBox1.Visible = true;
Image image = pictureBox1.Image;
byte[] bit = null;
bit = imageToByteArray(image);
product1 pd = new product1();
string category = tbCategoryName.Text;
string categorydesc = tbCategoryDescription.Text;
var c = new category { category_Name = category, category_Description = categorydesc };
pd.product_Name = tbProductName.Text;
decimal price = Convert.ToDecimal(tbProductPrice.Text);
pd.product_Price = price;
pd.product_Description = tbProductdescription.Text;
pd.product_Image = bit;
pd.category = c;
tsgentity.SaveChanges();
EquipmentFinder equipment = new EquipmentFinder();
equipment.productgridview.Refresh();
this.Close();
equipment.ShowDialog(this);
}
This is just an example. What your need to do is pull the current object from collection you are editing/saving using linq and then make the changed on the retrieved object and then update i.e.
public bool UpdateCustomer(Customer customer){
Customer cust = entities.Customers.FirstOrDefault(c => c.ID == customer.ID);
cust.Forname = customer.Forename;
cust.Surname = customer.Surname
entities.SaveChanges();
}
Have you checked the event handlers for those buttons? Are they wired into the correct buttons? It sounds like your edit button is firing the event handler for new products and it sounds like the add button is firing the event handler for editing a product. I would definitely check that first instead of looking for a work-around or hack to tolerate that.
精彩评论