I want to delete a row from gridview and database - I write some code but this code just delete the first row of my gridview. Please help me. I used Entity Framework and wpf C#.
using (AccountingEntities cntx = new AccountingEntities())
{
Producer item = this.grdProducers.SelectedItem as Producer;
cntx.DeleteObject(cntx.Producers.First(x => x.ID == item.ID));
cntx.SaveChanges();
dataPager.Source = cntx.Producers.ToList();
}
Maybe you should simple try:
cntx.DeleteObject(cntx.Producers.where(x => x.ID == item.ID));
// if you get my .where() code to return the entity's index you'll should be fine
This should invoke the appropiate lambda/linq. Since you use " where
" the expression is applied to every "Producer"-Entity x
matching item.ID
UPDATE:
From MSDN:
Deletes the record at the specified index from the data source.
DeleteObject(int rowIndex)
Well this explains a lot. Because this means, that your simply passing in the wrong argument. You need to loop through the whole Grid with a foreach or for and delete each entity with deleteObject and check before whether the object's id matches item.ID.
I am sure this would be easier by using Lambda/LINQ but I currently have no idea how this could be done otherwise.
I also found this quite interesting, you have to scroll down to "delete", the example is for a database, but still uses the grid as buffer so it should be the similiar problem.
I find the solution: when i open the dialog for confirming the delete action, selected item changed. i should select the entityId before opening the dialog . the below code show how to do this:
int unitTypeId = (this.grdUnitTypes.SelectedItem as UnitType).ID;
ConfirmWindowResult result = Helpers.ShowConfirm(this, SR.GlobalMessages.AreYouSureToDelete, SR.GlobalMessages.Warning);
if (result == ConfirmWindowResult.Yes)
{
using (AccountingEntities cntx = new AccountingEntities())
{
try
{
cntx.UnitTypes.DeleteObject(cntx.UnitTypes.First(x => x.ID == unitTypeId));
cntx.SaveChanges();
dataPager.Source = cntx.UnitTypes.ToList();
MessageBox.Show("Success");
}
catch (Exception ex)
{
MessageBox.Show("Error");
}
finally
{
cntx.Dispose();
}
}
}
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.