The last step is to add the code to the Delete button's
click event to delete a record.
1.
Switch back to Design view and double click on the Delete button to
generate the click event handler.
2.
Add the following code.
if (ddlUsers.SelectedItem.Value != "")
{
using (OrderDBContainer db = new OrderDBContainer())
{
UserAccount userAccount = new UserAccount();
userAccount.Id = Convert.ToInt32(ddlUsers.SelectedValue);
db.UserAccounts.Attach(userAccount);
db.ObjectStateManager.ChangeObjectState(userAccount, System.Data.EntityState.Deleted);
db.SaveChanges();
LoadUserDropDownList();
txtFirstName.Text = "";
txtLastName.Text = "";
lblInserted.Text = "";
lblUpdated.Text = "";
}
}
This code creates an instance of a UserAccount object and
sets its Id property to the value selected in the drop down list. To delete a
record you still need to attach it to the OrderDBContainer and tell the
ObjectStateManager what to do with the object when the SaveChanges method is
called. Once the record is deleted the drop down list is reloaded so the user
is removed and the textboxes and labels are cleared.