I feel like I had to invent a whole new way to do this because I couldn't find anything that did this the way I wanted to...
The basic process involves reading changes to cells and capturing information about those changes as they relate to the actual Entities in question and then persisting them to the database.
Here's the XAML. I didn't use databinding because I don't quite understand it yet and I'm on a bit of a deadline for this one so that's item number 1 on my to do list when I get a break.
Note that this project has been my first every foray into WPF. I've dabbled a bit in the past but I've really pushed myself to do things properly here... As properly as I know how anyway.
<DataGrid Name="dgUsers" Height="150"
CellEditEnding="dgUsers_CellEditEnding">
</DataGrid>
<StackPanel Name="spActions" Background="#2d2d30" Width="500" Height="50" Orientation="Horizontal" FlowDirection="RightToLeft">
<Button Name="btnCancel" Click="btnClose_Click" Content="Cancel" Style="{StaticResource CancelButton}" Height="30" Width="66" Margin="5,3,5,5"></Button>
<Button Name="btnSave" Click="btnSave_Click" Content="Save" Style="{StaticResource RoundedButtonGreen}" Height="30" Width="66" Margin="5,3,5,5"></Button>
<Label Name="lblResult"></Label>
</StackPanel>
Here's the C# codebehind:
Generate an entity from the changes that were made:
private List<User> UpdatedUsers { get; set; }
/// <summary>
/// Maintains a list of all changes made to all entities on the datagrid
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgUsers_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
if (UpdatedUsers == null) UpdatedUsers= new List<User>();
var _User = (User)e.Row.Item;
var Element = (TextBox)e.EditingElement;
if (String.Equals((string)e.Column.Header, "EmailAddress"))
{
User.EmailAddress = Element.Text;
}
else if (String.Equals((string)e.Column.Header, "Password"))
{
User.Password = Element.Text;
}
UpdatedUsers.Add(User);
}
From here the user clicks on a save button which loops through the changes captured in this list and updates the relevant records in the database:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
try
{
ApplicationDbContext Context = new ApplicationDbContext();
var Users = Context.Users.Where(x => x.CompanyId == (int)cmbCompanies.SelectedValue).ToList();
foreach (User User in Users)
{
foreach (User U in UpdatedUsers)
{
if (U.Id == User.Id)
{
User.EmailAddress = U.EmailAddress;
User.Password = U.Password;
}
Context.SaveChanges();
}
}
}
catch (Exception ex)
{
lblResult.Content = ex.Message;
}
}