Reputation: 59
I have created a local DB using the empty designer model, I've added the properties and the data. On the startup of my program the information is coming into the grid meaning that the DB is working fine.
I have a button when clicked it will read the selected item from the gridbox and remove it from the database. However when I try this I get the following error:
Additional information: Non-static method requires a target.
This is the code I am using:
private void btnRemoveManager_Click(object sender, RoutedEventArgs e)
{
if (DatagridManagerDisplay.SelectedValue != null)
{
ManagerTBL selected = DatagridManagerDisplay.SelectedValue as ManagerTBL;
var removeManager = from manager in db.ManagerTBLs
where manager.ManagerName == selected.ManagerName
select manager;
db.ManagerTBLs.RemoveRange(removeManager);
db.SaveChanges();
// Repeat the on window loaded method to refresh the grids
Window_Loaded(sender, e);
}
else
{
MessageBox.Show("Please select a team from the league");
}
}
Upvotes: 0
Views: 63
Reputation: 5148
You could use RemoveAll
like this.
ManagerTBL selected = (ManagerTBL)lbxManagerDisplay.SelectedItem;
if (selected != null)
{
db.ManagerTBLs.RemoveAll(mng => mng.ManagerName == selected.ManagerName);
db.SaveChanges();
}
Upvotes: 1
Reputation: 781
You can use SingleOrDefault
to get a single object matching your criteria, and then pass that to the Remove
method of your EF table.
private void btnRemoveManager_Click(object sender, RoutedEventArgs e)
{
if (lbxManagerDisplay.SelectedValue != null)
{
ManagerTBL selected = lbxManagerDisplay.SelectedValue as ManagerTBL;
var removeManager = db.ManagerTBLs.SingleOrDefault(x => x.ManagerName == selected.ManagerName); //returns a single item.
if (removeManager != null)
{
db.ManagerTBLs.Remove(removeManager );
db.SaveChanges();
}
// Repeat the on window loaded method to refresh the grids
Window_Loaded(sender, e);
}
else
{
MessageBox.Show("Please select a team from the league");
}
}
Hope it Helps!
Upvotes: 0