Please help I have 5 WPF Textbox and DataGrid, using Entity FrameWork
I m experiencing problem when I try to updating UI form this is my ADO.NET Entity FrameWork model Entity Products with Column with the following columns
ProductID int PK,
ProductName nvarchar(50),
ProductCode nvarchar(50),
ProductType nvarchar(50),
Description nvarchar(50),
CreateDate DateT开发者_运维问答ime
and ProductPrice money
and I have 5 TextBoxes which contain txtPName,txtDescription,txtCode,txtPrice,txtType,Datagrid to list all product from Database and btnupdate.and my textboxes are all binded correctly with datagrid, when I select any Item from the Datagrid it load the selectedItem to the all 5 txtboxes so my problem started when I try to edit data from textboxes and click update button to update the the database.
this is my xaml code from UI
and xaml.cs for update button
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
if (ProductList.SelectedIndex >= 0)
{
//get selected information first
Product newProduct = new Product();
newProduct.ProductName = txtName.Text.Trim();
newProduct.ProductPrice = (decimal)(12.00);//decimal.Parse(txtPrice.Text);
newProduct.ProductType = txtType.Text.Trim();
newProduct.ProductCode = txtProductCode.Text.Trim();
newProduct.Description = txtDescription.Text.Trim();
newProduct.CreateDate = DateTime.Now;//
Product product = ProductList.SelectedValue as Product;
//col.Remove(product);
//col.Add(newProduct);
db.SaveChanges();
MessageBox.Show("Row is updated successfully");
}
else
{
MessageBox.Show("Select");
}
}
the update code does not update the database..... Please Guys I need help from brianbk email kagisobk@gmail.com
You don't create a new instance to update an existing entity, just apply the edits to the edited object, Entity Framework will track any changes you do to entities and will update the DB as appropriate when calling SaveChanges().
So just get the selected object as you did then transfer the new values to its properties and finally you call SaveChanges:
Product product = ProductList.SelectedValue as Product;
product.ProductName = txtName.Text.Trim();
product.ProductPrice = decimal.Parse(txtPrice.Text);
....
db.SaveChanges();
But the recommended and more efficient approach that you should be using is to use Data Binding to let WPF transfer the data between your entity and controls in both directions (Load/Update).
then in update button you just need to call SaveChanges().
精彩评论